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

how to correctly display the integral on the graph?

我计算了积分,我想把它显示在图表上,但我不知道应该如何正确地把它放在图表上。在我看来,仅 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,b, x1) - II(a,b, 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, b, x[0], x[1:]), '--r')
plt.show()

如果您还没有参加 tour,了解如何对收到的答案进行分类。

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