Haque1
Haque1

Reputation: 593

Infinite loop code

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
}

Upvotes: 0

Views: 108

Answers (2)

gerrytan
gerrytan

Reputation: 41143

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
}

Upvotes: 1

Chris Gerken
Chris Gerken

Reputation: 16390

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.

Upvotes: 4

Related Questions