SymPy outputs a numerical result when a symbolic expression is expected

佐手、 提交于 2020-01-15 01:58:10

问题


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)

回答1:


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.



来源:https://stackoverflow.com/questions/59250127/sympy-outputs-a-numerical-result-when-a-symbolic-expression-is-expected

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!