绘制给定区间围绕 x 位置的积分

问题描述 投票:0回答:1

我想绘制一个函数在位置 x 周围具有间隔的积分。

我用 scipy.integrate.quad 和 scipy.integrate.cumtrapz 尝试过这个,但它们似乎都不起作用。我认为这应该是一个非常常见的任务,但我找不到任何可以帮助我的示例代码。下面的代码是我尝试进行的尝试,但它不会返回有用的结果。

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

x = np.linspace(0, 3, num=1000)
def f(v):
    f=np.cos(np.pi*v)+1
    return f
def y_int(v):
    y_int = scipy.integrate.cumtrapz(f(v), x, initial=0)
    return y_int
a=0.5
plt.plot(x, y_int(x+a)-y_int(x-a), 'r-')
plt.plot(x, f(x), 'b-')
plt.show()
python matplotlib scipy numerical-integration
1个回答
0
投票

更新

我改用

scipy.integrate.quad
,因为
cumtrapz
导致的问题超过零。请注意三元条件以给出
initial = 0
提供的
cumtrapz
逻辑。

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

x = np.linspace(0, 3, num = 1000)
a = 0.5
f = lambda v: np.cos(np.pi * v) + 1

def y_int(v):
    integral = scipy.integrate.quad(f, v - a if v > a else 0, v + a)
    return integral[0]

plt.plot(x, f(x), 'b-')
plt.plot(x, np.array(map(y_int, x)), 'r-')
plt.show()

原创

我重新格式化/调整了你的代码,这样我就可以使用更容易验证的值,比如使你的间隔为 0 到 2pi。为了检查目的,我还删除了您的公差区间,并且我相信您在

scipy.integrate.cumtrapz
函数中调用“v”“x”时犯了一个错误。这里已经清理干净了:

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

x = np.linspace(0, np.pi * 2, num = 1000)

def f(v):
    f=np.cos(np.pi * v)
    return f

def y_int(v):
    y_int = scipy.integrate.cumtrapz(f(v), v, initial=0)
    return y_int

plt.plot(x, f(x), 'b-') #plot the function from 0 to 2pi
plt.plot(x, y_int(x), 'r-')
plt.show()

输出:

这会产生我期望函数下的累积面积的样子,因为它以 pi/3 为间隔将自身归零,并且面积每 (2/3)pi 增加一倍。

这是你的代码,稍微清理一下,范围也从 1 到 4(间隔为 0 到 3,x 间隔交叉到负数,初始设置为 0 会给出奇怪的结果):

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

x = np.linspace(1, 4, num = 1000)
a = 0.5

def f(v):
    f=np.cos(np.pi * v) + 1
    return f

def y_int(v):
    y_int = scipy.integrate.cumtrapz(f(v), v, initial=0)
    return y_int

plt.plot(x, f(x), 'b-')
plt.plot(x, y_int(x + a) - y_int(x - a), 'r-')
plt.show()

输出:

© www.soinside.com 2019 - 2024. All rights reserved.