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)
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 integratee^(-x^2)
. Let's test: