python - 如何在 Python 中使用 x^2 进行(空中飞人)集成?

标签 python numpy matplotlib math integration

我的任务是先做一个积分,然后用 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)

enter image description here

现在我想集成这个函数来得到这个:F(x)=(1/3)x^3 和图片:

enter image description here

这应该是最后的输出:

enter image description here

有人能解释一下如何用 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()

它为您提供所需的结果,但您应该自己指定的任意常量除外。

plot

为了更好地衡量,虽然在这种情况下不相关,但请注意,如果与小数步一起使用,np.arange() 不会提供稳定的结果。通常,人们会改用 np.linspace()

关于python - 如何在 Python 中使用 x^2 进行(空中飞人)集成?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62501628/

相关文章:

python - 许多模块都需要连接到 Azure SQL DB - 如何连接?

python - Matplotlib 中的空、零和非零像素表示

python - numpy 数组索引的意外行为

arrays - 快速组合多幅图像的(x,y)像素值的方法?

python - 了解matplotlib : plt,图,ax(arr)?

python - 将图片和绘图与带有 alpha channel 的 matplotlib 结合起来

python - 在 matplotlib 的颜色条中修复 ylabel 位置

具有特定扩展名 "html"的 Python 文件 IO 失败

python - 这个 python 脚本可以缩短/优化,如何?

python - 如何在 Jupyter Notebook 中的 Python 段落中打开 Web 浏览器