user4332869
user4332869

Reputation: 23

defining integral using trapezoidal rule(beginner)

My programm aims in defining the integral of a given function between two numbers (x1,x2),using n trapezoids.As it seems,my department's auto evaluating programm gives different answers than the ones of mine.Problem is that i cant find anything wrong in my code...

def funct(x):
    val= -(1./6)*(x-1)*(x-2)*(x+2)*(x-4)
    return val


x1,x2,n=input()
Dx=float(x2-x1)/n
Sum=0
i=x1+Dx
while i<x2:
    val=funct(i)
    Sum+=val
    i+=Dx
Sum=2*Sum
val1=funct(x1)
val2=funct(x2)
S=(Dx/2)*(val1+val2+Sum)
print "%.3f" %S  

Upvotes: 2

Views: 104

Answers (2)

gboffi
gboffi

Reputation: 25023

Due to rounding issues, your while cycle always includes last value of x, try using exact integer arithmetic

x0, x1 = -88.787529, 83.494648
n = 1942

dx = (x1-x0)/n
s = 0
i = 1
while i < n:

   # if we allow i == n, in the following row we'll have
   #   x0 + n*dx = x0 + n * (x1-x0) / n = x0 + x1 - x0 = x1
   # but we want to exclude the last term

   s = s + funct(x0+i*dx)
   i = i + 1
result = (s + funct(x0)/2.0 + funct(x1)/2.0)*dx

Upvotes: 1

Psirus
Psirus

Reputation: 1473

I know this is probably some sort of homework question, but in general, don't reinvent the wheel:

import numpy

def funct(x):
    return -(1./6)*(x-1)*(x-2)*(x+2)*(x-4)

x1, x2 = -88.787529, 83.494648
n = 1942
# n "panels", n+1 points
x = numpy.linspace(x1, x2, n+1)
y = funct(x)

result = numpy.trapz(y, x)

Upvotes: 0

Related Questions