如何在 Python 中绘制 e^(-t^2) 从 x=0 到 x=3 的积分?

How do I plot the integral of e^(-t^2) from x=0 to x=3 in Python?

我需要在 Python 中计算和绘制下面的积分:

函数 e^(-t^2) 从 x=0 到 x=3 的积分

到目前为止,我已经成功地使用辛普森法则计算了积分。接下来我要努力的是绘制 e^(-t^2) 对 x 从 x=0 到 x=3 的积分(见上图)。

这是我编写的用于计算积分的代码 -

from math import exp

def f(t):
    return exp(-(t**2))

a = 0
b = 3
h = 0.1
N = int((b-a)/h)
s_even = 0
s_odd = 0

for k in range(1,N,2):
    s_odd += f(a+k*h)

for k in range(2,N,2):
    s_even += f(a+k*h)

s = f(a) + f(b) + 4*s_odd + 2*s_even
Integral = h*s/3
print(Integral)

然后我如何创建这个积分的图表?

这是我编写的脚本,用于执行您的计算并使用 PyQtGraph:

绘制它
from pyqtgraph.Qt import QtGui, QtCore
import pyqtgraph as pg

from math import exp

class I:

    def f(self,t):
        return exp(-(t**2))

    def __init__(self, a = 0, b = 3, h = 0.1):
        N = int((b-a)/h)
        s_even = s_odd = 0
        for k in range(1,N,2):
            s_odd += self.f(a+k*h)

        for k in range(2,N,2):
            s_even += self.f(a+k*h)

        s = self.f(a) + self.f(b) + 4*s_odd + 2*s_even
        self.I = h*s/3

    def __str__(self):
        return "I: %s" % self.I

def plot(array):
    app = QtGui.QApplication([])
    win = pg.GraphicsWindow(title="Basic plotting examples")
    win.resize(1000,600)
    win.setWindowTitle('pyqtgraph example: Plotting')

    # Enable antialiasing for prettier plots
    pg.setConfigOptions(antialias=True)

    p1 = win.addPlot(title="Basic array plotting", y=array)

    QtGui.QApplication.instance().exec_()

def main():
    a=0
    b=a+0.001
    points=[]
    while(a<3):
        points.append(I(a,b).I)
        a=b
        b=a+0.001
    plot(points)


## Start Qt event loop unless running in interactive mode or using pyside.
if __name__ == '__main__':
    main()

这是它绘制的图形:

感谢您对 Red Cricket 的帮助。看起来您绘制的可能是函数 e^(-t^2) 而不是该函数的积分。尽管如此,我想我已经解决了;我发现 scipy 有一个集成函数:

from math import exp
from numpy import arange
from scipy import integrate

def f(t):
    return exp(-(t**2))

a = 0
b = 3
h = 0.1
N = int((b-a)/h)

s_even = 0
s_odd = 0

for k in range(1,N,2):
    s_odd += f(a+k*h)

for k in range(2,N,2):
    s_even += f(a+k*h)

s = f(a) + f(b) + 4*s_odd + 2*s_even
I = h*s/3

function = []
x = []
for t in arange(0,4,h):
    function.append(f(t))
for i in arange(0,4,h):
    x.append(i)

function_int = integrate.cumtrapz(function,x,initial=0)

plot(x,function_int)
show()
print(I)

这会生成积分图并打印积分本身的最终值。万岁!