-1

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)
DSM
  • 342,061
  • 65
  • 592
  • 494
Robert
  • 1
  • 3
  • what errors are you getting? If there's nothing wrong with your code, but you are getting the wrong answer, try printing out some intermediate values to see where the errors are in your logic. – Matt Coubrough Oct 22 '14 at 04:26

1 Answers1

2

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
DSM
  • 342,061
  • 65
  • 592
  • 494