martinkors
martinkors

Reputation: 43

SymPy outputs a numerical result when a symbolic expression is expected

I'ld like my SymPy results to be displayed as precise results and not as decimal results. I looked through the SymPy documentation, but couldn't find anything helpful.

To illustrate the problem, here is some example code:

from sympy import *
u = symbols("u")
integrate((1+u)**(1/2), (u, 0, 1))

Output:

1.21895141649746

Expected result:

(4/3)*sqrt(2)-(2/3)

Upvotes: 4

Views: 377

Answers (1)

JohanC
JohanC

Reputation: 80329

The problem is that SymPy will simplify expressions containing floats and so removes those symbolic expressions. Although the expression doesn't look like a float, the division 1/2 is done with standard Python, internally represented as 0.5.

The solution is to first convert one of the parts of the fraction to a SymPy object. The easiest way is with the function S, as in:

from sympy import *
u = symbols("u")
print(integrate((1+u)**(S(1)/2), (u, 0, 1)))

which outputs the desired -2/3 + 4*sqrt(2)/3.

The gotcha section of the documentation tries to explain this behavior.

Upvotes: 7

Related Questions