sympy 中表达式的数值

numerical value for an expression in sympy

sympy 给我以下表达式:

2.8*x**2 - 4.0*x*Integral(1.0*x**2*sqrt(-x**2 + 1), (x, -1.0, 0.0)) + 1.33333333333333*x + 0.133333333333333

我希望 sympy 给我系数的数值。我怎样才能做到这一点? .evalf 和 N() 无效。

这是我的代码

from numpy import *
from sympy import *
from matplotlib.pyplot import *

x = Symbol ('x')

#The function we are required to approximate
f1 = -1.0*x
f2 = 1.0*x


phi_0=1.0
phi_1 = 2.0*x
phi_2 = 4.0*x*x-1

w = 1.0*sqrt(1.0-x*x)

#compute the coefficient

c_0 = integrate(f1*phi_0*w, (x, -1.0, 0.0))+integrate(f2*phi_0, (x, 0.0, 1.0)) 
c_1 = integrate(f1*phi_1*w, (x, -1.0, 0.0))+integrate(f2*phi_1, (x, 0.0, 1.0)) 
c_2 = integrate(f1*phi_2*w, (x, -1.0, 0.0))+integrate(f2*phi_2, (x, 0.0, 1.0)) 

fapprox2 = c_0*phi_0+c_1*phi_1+c_2 *phi_2

问题是您的积分没有(或有难解)解析解,因此 SymPy 返回未计算的积分表达式。​​

如果要数值作为答案,为什么不用scipy.integrate.quad,例如:

from scipy.integrate import quad
from numpy import *
from sympy import *

x = Symbol('x')

#The function we are required to approximate
f1 = -1.0*x
f2 = 1.0*x


phi_0= 1.0
phi_1 = 2.0*x
phi_2 = 4.0*x*x-1

w = 1.0*sqrt(1.0-x*x)

#compute the coefficient

lf10 = lambdify((x,), f1*phi_0*w, 'numpy')
lf11 = lambdify((x,), f1*phi_1*w, 'numpy')
lf12 = lambdify((x,), f1*phi_2*w, 'numpy')

lf20 = lambdify((x,), f2*phi_0, 'numpy')
lf21 = lambdify((x,), f2*phi_1, 'numpy')
lf22 = lambdify((x,), f2*phi_2, 'numpy')

c_0 = quad(lf10, -1, 0)[0] + quad(lf20, 0, 1)[0]
c_1 = quad(lf11, -1, 0)[0] + quad(lf21, 0, 1)[0]
c_2 = quad(lf12, -1, 0)[0] + quad(lf22, 0, 1)[0]

print c_0, c_1, c_2
# 0.833333333333 0.273967584968 0.7