如何在图形上正确显示积分?

问题描述

我计算了积分,我想在图表上显示它,但我想知道它应该如何正确放置在图表上。在我看来,仅 plt.plot() 是不够的,或者我错了,我想知道在图表中显示此结果的正确方法

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


def integral(x,a,b):
    return a * np.log(x + b) 


a = 3
b = 2

I = quad(integral,1,5,args=(a,b))
print(I)

plt.plot()
plt.show()

解决方法

我假设您了解微积分,但不太了解编程。 matplotlib.plot 只绘制数据,因此您必须使用要绘制的数据点构建一个数组。 quad 的结果也是一对数字、定积分近似和数值误差的估计界限。

如果要绘制函数的反导数,则必须计算要显示的每个点的积分。

这是一个示例,我创建了一个数组并计算每个元素 a[i] < x < a[i+1] 之间的积分,然后使用累积和来获得曲线。

作为参考,我还绘制了解析积分

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


def integral(x,a,b):
    return a * np.log(x + b)


def II(a,b,x0,x1 = None):
    if x1 is None:
        # indefinite integral
        return a * ((x0 + b) * np.log(x0 + b) - x0)
    else:
        # definite integral
        return II(a,x1) - II(a,x0)
a = 3
b = 2
# plot 100 points equally spaced for 1 < x < 5
x = np.linspace(1,5,100)
# The first column of I is the value of the integral,the second is the accumulated error
# I[i,0] is the integral from x[0] to x[i+1].
I = np.cumsum([quad(integral,x[i],x[i+1],args=(a,b)) for i in range(len(x) - 1)],axis=0);

# Now you can plot I
plt.plot(x[1:],I[:,0])
plt.plot(x[1:],II(a,x[0],x[1:]),'--r')
plt.show()

what you should see

如果您还没有,也请选择 tour,了解如何对收到的答案进行分类。

我希望这能回答您的问题。