title: Trapezoid Rule in Python
body: <p>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.</p>
  
  <p>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.</p>
  
  <p>I am using Wing IDE.</p>
  
  <p>This is what I have so far</p>
  
  <pre><code># 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)
  </code></pre>
  
  <p>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?</p>