Saturday, 28 September 2013

Trapezoid Rule in Python

Trapezoid Rule in Python

I am trying to write a program using Python v. 2.7.5 that will compute the
area under the curve y=sin(x) between x = 0 and x = pi. Perform this
calculation varying the n divisions of the range of x between 1 and 10
inclusive and print the approximate value, the true value, and the percent
error (in other words, increase the accuracy by increasing the number of
trapezoids). Print all the values to three decimal places.
I am not sure what the code should look like. I was told that I should
only have about 12 lines of code for these calculations to be done.
I am using Wing IDE.
This is what I have so far
# base_n = (b-a)/n
# h1 = a + ((n-1)/n)(b-a)
# h2 = a + (n/n)(b-a)
# Trap Area = (1/2)*base*(h1+h2)
# a = 0, b = pi
from math import pi, sin
def TrapArea(n):
for i in range(1, n):
deltax = (pi-0)/n
sum += (1.0/2.0)(((pi-0)/n)(sin((i-1)/n(pi-0))) +
sin((i/n)(pi-0)))*deltax
return sum
for i in range(1, 11):
print TrapArea(i)
I am not sure if I am on the right track. I am getting an error that says
"local variable 'sum' referenced before assignment. Any suggestions on how
to improve my code?

No comments:

Post a Comment