问题
I'm encountering some problems using sympy, here is my code:
from sympy import integrate as inter
import sympy as sp
from sympy import symbols
def f(x):
f1 = (sp.exp(-x ** 2)) / (1 + x ** 2)
f2 = (2 * (sp.cos(x)) ** 2) / (1 + (x - 4) ** 2)
f = f1 + f2
return(f)
def integrate_f_from0(b):
x = symbols('x')
a = inter(f(x), (x, 0, b))
return(a)
The error I get upon running the integrate_f_from0 function is:
AttributeError: module 'sympy' has no attribute 'polys'
What is causing this error?
回答1:
In SymPy 1.1.1 your code works as expected: integrate_f_from0(3) returns
Integral((2*x**2*exp(x**2)*cos(x)**2 + x**2 - 8*x + 2*exp(x**2)*cos(x)**2 + 17)*exp(-x**2)/((x**2 + 1)*(x**2 - 8*x + 17)), (x, 0, 3))
Which means, SymPy could not find a symbolic expression for that integral, so it returns it unevaluated (although transformed in the process of searching for antiderivative).
A quick check with Wolfram Alpha confirms there is no antiderivative in terms of elementary functions.
Suggestions:
If you have the sum of two complicated functions, try integrating it one term at a time. It does not help in this case, but in general you'll at least have an idea of what part of the expression fails to have an elementary antiderivative.
To find the integral numerically, use
N(Integral(f(x), (x, 0, 3)))(returns 1.24063...) though of course, for numeric integration one is more likely to use SciPy.
来源:https://stackoverflow.com/questions/47872010/attributeerror-module-sympy-has-no-attribute-polys