【问题标题】:how to correctly display the integral on the graph?如何在图表上正确显示积分?
【发布时间】:2021-08-18 23:24:26
【问题描述】:

我计算了积分,我想将它显示在图表上,但我想知道它应该如何正确放置在图表上。在我看来,仅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()

【问题讨论】:

  • 你只想绘制这个单点?
  • plt.plot() 中也可能缺少I
  • @Nk03 我只是想把积分放在图上,只是不知道把积分放在对数图的形式上是否够用,还是有其他函数可以呈现积分。
  • @JayPatel 是的,我知道我在那里失踪了,但我想知道是否足以将积分以对数函数的形式(如代码中)或是否存在是重新排列积分的其他函数。
  • 没有客观正确的方法。这取决于用户的目标。如果您制作一个情节并解释您认为它在哪些方面不正确,也许我们可以帮助您。

标签: python numpy matplotlib graph scipy


【解决方案1】:

我假设您知道微积分,但对编程知之甚少。 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,了解如何对收到的答案进行分类。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多