Troubleshooting a Trap: Debugging the Trapezium Rule

Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
1 reply · 1K views
whatisreality
Messages
286
Reaction score
1
This is not giving me the right answer! I have checked for errors like integer division and rounding, but can't find any. I am aware the comments are slightly inaccurate and they will be improved. But what's wrong with the actual code?
Java:
//This method uses the trapezium rule to calculate the integral
   //a is the lower limit, b the upper limit, c is the power of x in the function, N the number of trapezia
   //Returns the result of the integral
   public static double trapeziumRule(double a, double b, double c, int N){

     double h = (b-a)/(N-1);             //h is the width of a single trapezium
     double x = 0.5*(f(a,c)+f(b,c));           //x is the average height of the trapezium
     for(int i=2; i<N-1; i++){

       x += f(a+h*i,c);
     }
     double integral = h*x;
     return integral;
It's probably something in the actual maths... should i run from 2 to N-2? I clearly don't know how to use sum notation properly, since I can't convert ##\sum_{i=2}^{N-1}## into a for statement correctly.

Actually, is that the problem? Should it be i<=N-1? And i starts from 1? That would also affect my formula for h.

Except that doesn't work either.
 
Last edited:
Physics news on Phys.org
Whoops, found the flaw. Difference in the meaning of N in my course notes and the meaning of N in my code!