python计算积分

python有多个方法计算积分,下面介绍其中三个,以下式为例:

方法一:直接用numpy计算

start = 1
stop = 2
length = 101
x = np.linspace(start, stop, length)
y = x**2
result = sum(y*(stop-start)/length)
print(result)

输出结果:

2.335

方法二:用sympy计算

from sympy import *
x = symbols("x")
print(integrate(x**2, (x, 1, 2)))    # integer的参数(函数,(变量,起始位置,终止位置))

输出结果:

7/3

方法三:用 scipy计算

from scipy import integrate
def f(x):
    return x**2
print(integrate.quad(f,1,2))  # quad方法会返回精确的值和误差

输出结果:

(2.3333333333333335, 2.590520390792032e-14)
原文地址:https://www.cnblogs.com/picassooo/p/12586191.html