0

I'm trying to code an Integrate class which will give me the integral of a function using the Trapezoidal rule. For some reason, the code I have never resolves to a value and stays stuck in the "sum +=" step:

public static double Trap(int exponent, int a, int b, int n) {
    double h = (double) (b-a)/n;

    double sum = 0;
    for(int i = a; i <= b; i+=h)
        sum += (Math.pow(i, exponent) + Math.pow(i+1, exponent))/2; //trouble!

    return h * sum;
}

public static void main(String[] args) {
    System.out.println(Trap(3,1,3,10)); //integral of x^3 from 1 to 3, 
    divided into 10 parts
}
3
  • 2
    Don't try to "bold" code. Use a comment instead. Commented Mar 26, 2013 at 1:45
  • 1
    I could imagine that h is always 0. Commented Mar 26, 2013 at 1:48
  • Got it. Changed everything to a double Commented Mar 26, 2013 at 1:52

2 Answers 2

4

You declared i as an int, so when you add a double (1/3) to it, it rounds down and keeps the same value.

Change i to be a double.

In fact, you ought to make everything a double.

Sign up to request clarification or add additional context in comments.

1 Comment

"you ought to make everything a double"...take that with a grain of salt though. There are many cases when you should be using int instead of double.
1

Your code has a problem with type casting, specifically on the loop increment expression i+=h.

In your case, if h is a double with value 0.2, and i is integer, 0.2 will be casted to 0.

To illustrate this, please try run following code example:

public static void main(String[] args) {

    int i = 1;
    i += 0.2;

    System.out.println(i); // will always output 1
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.