问题
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