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

时间:2018-11-24 06:11:01

标签: python math plot physics integral

我需要在Python中同时计算和绘制积分:

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

到目前为止,我已经设法使用Simpson规则来计算积分。我正在努力的下一位是绘制从x = 0到x = 3的e ^(-t ^ 2)vs x的积分(请参见上图)。

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

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)

然后如何创建此积分图?

2 个答案:

答案 0 :(得分:0)

这是我编写的脚本,用于执行您的计算并使用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()

这是它绘制的图形:

enter image description here

答案 1 :(得分:0)

感谢您对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)

这将生成积分图,并打印积分本身的最终值。哇!