Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python sympy Evaluating When Asked Not To

Tags:

python

sympy

This works as expected:

>>> from sympy.parsing.sympy_parser import parse_expr 
>>> parse_expr("2**3"), parse_expr("2**3", evaluate=False)
(8, 2**3)

This, however, not:

>>> from sympy.parsing.sympy_parser import parse_expr
>>> parse_expr("sqrt(9)"), parse_expr("sqrt(9)", evaluate=False)
(3, 3)

I would expect:

(3, sqrt(9))

Any ideas, why?

like image 308
major4x Avatar asked Oct 12 '25 19:10

major4x


1 Answers

The evaluate flag to parse_expr only affects the direct evaluation of the expression. sqrt(x) is short for x**Rational(1, 2), which isn't part of the expression parsing.

You can use the with evaluate(False) decorator to prevent the power in the sqrt function from evaluating:

>>> with evaluate(False):
...     print(parse_expr('sqrt(9)', evaluate=False))
sqrt(9)
>>>

(I kept the evaluate=False flag, but it's probably not actually needed)

like image 169
asmeurer Avatar answered Oct 16 '25 09:10

asmeurer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!