我的任务是首先进行积分,然后与 Python 进行梯形积分 f(x)=x^2
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(-10,10)
y = x**2
l=plt.plot(x,y)
plt.show(l)
现在我想整合这个函数来得到这个:F(x)=(1/3)x^3与图片:
这应该是最后的输出:
有人可以解释一下如何用 python 得到 f(x)=x^2 的反导数 F(x) 吗? 我想通过正常积分和梯形积分来做到这一点。对于从 (-10 到 10) 的梯形积分,步长大小为 0.01(梯形的宽度)。最后我想在这两种情况下得到函数 F(x)=(1/3)x^3 。我怎样才能达到这个目标?
谢谢你帮助我。
有两个关键观察结果:
F(x)
scipy.integrate.trapz()
来定义积分函数:
import numpy as np
from scipy.integrate import trapz
def numeric_integral(x, f, c=0):
return np.array([sp.integrate.trapz(f(x[:i]), x[:i]) for i in range(len(x))]) + c
scipy.integrate.cumtrapz()
(从上面进行计算):
import numpy as np
from scipy.integrate import cumtrapz
def numeric_integral(x, f, c=0):
return cumtrapz(f(x), x, initial=c)
绘制如下:
import matplotlib.pyplot as plt
def func(x):
return x ** 2
x = np.arange(-10, 10, 0.01)
y = func(x)
Y = numeric_integral(x, func)
plt.plot(x, y, label='f(x) = x²')
plt.plot(x, Y, label='F(x) = x³/3 + c')
plt.plot(x, x ** 3 / 3, label='F(x) = x³/3')
plt.legend()
它为您提供所需的结果,但任意常数除外,您应该自己指定该常数。
为了更好地衡量,虽然与本例无关,但请注意,如果与分数步骤一起使用,
np.arange()
不会提供稳定的结果。通常,人们会使用 np.linspace()
来代替。
scipy 中的
cumtrapz
函数将使用梯形积分提供反导数:
from scipy.integrate import cumtrapz
yy = cumtrapz(y, x, initial=0)
# make yy==0 around x==0 (optional)
i_x0 = np.where(x >= 0)[0][0]
yy -= yy[i_x0]
梯形积分
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(-10, 10, 0.1)
f = x**2
F = [-333.35]
for i in range(1, len(x) - 1):
F.append((f[i] + f[i - 1])*(x[i] - x[i - 1])/2 + F[i - 1])
F = np.array(F)
fig, ax = plt.subplots()
ax.plot(x, f)
ax.plot(x[1:], F)
plt.show()
这里我应用了理论公式
(f[i] + f[i - 1])*(x[i] - x[i - 1])/2 + F[i - 1]
,而积分是在块中完成的:
F = [-333.35]
for i in range(1, len(x) - 1):
F.append((f[i] + f[i - 1])*(x[i] - x[i - 1])/2 + F[i - 1])
F = np.array(F)
注意,为了绘制
x
和F
,它们必须具有相同数量的元素;所以我忽略了 x
的第一个元素,所以它们都有 199
元素。这是 梯形方法 d 的结果:如果对 f
元素的数组 n
进行积分,您将获得 F
元素的数组 n-1
。此外,我将 F
的初始值设置为 -333.35
处的 x = -10
,这是积分过程中的任意常数,我决定该值是为了在原点附近传递函数。
分析整合
import sympy as sy
import numpy as np
import matplotlib.pyplot as plt
x = sy.symbols('x')
f = x**2
F = sy.integrate(f, x)
xv = np.arange(-10, 10, 0.1)
fv = sy.lambdify(x, f)(xv)
Fv = sy.lambdify(x, F)(xv)
fig, ax = plt.subplots()
ax.plot(xv, fv)
ax.plot(xv, Fv)
plt.show()
这里我通过
sympy
模块使用符号数学。集成是在块中完成的:
F = sy.integrate(f, x)
注意,在这种情况下,
F
和x
已经具有相同数量的元素。而且,代码更简单。