Trapezoid and Simpson rule in Python?

随声附和 提交于 2019-12-25 17:45:09

问题


I have to write the trapezoid and simpson rule in python for the function e^((-x)^2).

Here's what I got so far. The answer it gives out is 8218.7167913 but the answer according to my teacher is something like 1.77251356.....

Where did I go wrong?

from numpy import *

def f(x):
    return e**((-x)**2)

def trapezoid(f, a, b, n):
    deltax = float(b - a)/(n)
    h = float(b - a) / n
    s = 0.0
    s += f(a)/2.0
    for i in range(1, n):
        s += f(a + i*h)
    s += f(b)/2.0
    return s * h

print trapezoid(f, -3, 3, 6)

回答1:


Look at your function: e^((-x)^2). The negative sign isn't doing anything because you're squaring it away immediately. That seems strange. More likely is that you were supposed to integrate e^(-x^2). Let's test:

>>> trapezoid(lambda x: e**((-x)**2), -3, 3, 1000)
2889.3819494560144
>>> trapezoid(lambda x: e**(-x**2), -3, 3, 1000)
1.7724146920763713


来源:https://stackoverflow.com/questions/26500293/trapezoid-and-simpson-rule-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!