【问题标题】:How to integrate Simpsons rule using Scipy to plot a 1D graph如何使用 Scipy 集成辛普森一家规则来绘制一维图
【发布时间】:2019-04-22 09:49:01
【问题描述】:

我需要一些帮助,我有一个任务是使用辛普森规则对函数的集成进行编码。我需要使用内置的 scipy integrationsimps 函数来绘制一维图。我只是不知道从哪里开始。我想我必须为对应于 x 的每个值的函数获取 y 的每个值的列表/数组:例如

如果我的函数是 x^2 那么当 x 为 0 y 为 0, x 是 1 y 是 1, x 是 2 y 是 4, 等等,直到一个巨大的极限......

然后使用integrate.simps(y,x),其中y是如上所示的所有y值,x是所有对应的x值。

但是,我根本无法让它工作...有没有人有任何使用integrate.simps(y,x) 的x^2 函数的图表示例?

这是我到目前为止所得到的:

import numpy as np
from scipy import integrate
import matplotlib.pyplot as plt

x = np.linspace(-10,10,N)
N = 100

yarray = []

def f(x):
    return x**2

for i in x :
    y = f(i)
    yarray.append(y)

print(yarray)


E = integrate.simps(yarray,x)
print(E)

plt.plot(x,E)

【问题讨论】:

  • 绘制一维图是什么意思,你是想绘制 x^2、x^2 的积分还是别的什么?
  • 我正在尝试使用integrate.simps() 绘制x^2 的积分

标签: python scipy numerical-methods integral simpsons-rule


【解决方案1】:

基本上,您需要计算 x 的每个范围的积分值,从 [-10,-10] 到 [-10,10]

此示例代码绘图

import numpy as np
from scipy import integrate
import matplotlib.pyplot as plt

def f(x):
    return x**2

N = 100
x = np.linspace(-10,10,N)


integrals = []
x_range = []
y_range = []
for i in x:
    x_range.append(i)
    y_range.append(f(i))
    integral = integrate.simps(y_range, x_range)
    integrals.append(integral)

plt.plot(x, integrals)
plt.show()

总结一下

import numpy as np
from scipy import integrate
import matplotlib.pyplot as plt

def integrals(f, xs):
    x_range = []
    y_range = []
    results = []
    for x in xs:
        x_range.append(x)
        y_range.append(f(x))
        integral = integrate.simps(y_range, x_range)
        results.append(integral)
    return results

def f(x, b):
    return (x-b)**2

xs = np.linspace(-10, 10, 100)

plt.plot(xs, integrals(lambda x: f(x, 0), xs), label='b=0')
plt.plot(xs, integrals(lambda x: f(x, 2), xs), label='b=2')
plt.plot(xs, integrals(lambda x: f(x, 4), xs), label='b=4')
plt.title('$y(x) = \int_{-10}^{x}(t-b)^2dt$')
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.show()

你会得到

【讨论】:

  • 谢谢!效果很好,如果我的函数中有一个变量会发生什么?例如 (x-b)^2 其中 b 正在变化
  • 在 X=0 的情况下 Y 不应该为零吗?是什么导致一切都发生了变化?
猜你喜欢
  • 2018-05-19
  • 2016-05-05
  • 1970-01-01
  • 2013-08-15
  • 1970-01-01
  • 2021-04-19
  • 1970-01-01
  • 1970-01-01
  • 2021-07-03
相关资源
最近更新 更多