Problem with Infinite Loop in Half-Interval/Bisection Method

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • krabina1988
    New Member
    • Oct 2011
    • 9

    Problem with Infinite Loop in Half-Interval/Bisection Method

    Can anyone assist me with my half-interval/bisection program. It does not terminate the while loop. Here is the code I've done so far.


    import java.util.*;

    public class HIM
    {
    public static void main(String args[])
    {
    Scanner sc = new Scanner(System. in);
    double upper, lower, ans, err, err2=1, temp1=0, temp2=0, temp3=0, temp4=0, temp5=0, x;
    System.out.prin t("Enter Power of Polynomial: ");
    int pow = sc.nextInt();
    System.out.prin t("Enter Termination Criterion: ");
    err = sc.nextDouble() ;
    int arr[] = new int[(pow+1)*2];
    int iter = 1;

    for(int j=1; j<arr.length;j+ +)
    {
    System.out.prin t("\nEnter Coefficient: ");
    arr[j-1] = sc.nextInt();
    System.out.prin t("Enter Exponent: ");
    arr[j] = sc.nextInt();
    j++;
    }

    System.out.prin t("\nInput Formula: " + arr[0] + "x^" + arr[1] + " + " + arr[2] + "x^" + arr[3] + " + " + arr[4] + "x^" + arr[5] + " + " + arr[6] + "x^" + arr[7] + " + " + arr[8] + "x^" + arr[9] + " + " + arr[10] + "x^" + arr[11]);

    System.out.prin t("\nEnter Upper Estimate of x: ");
    upper = sc.nextDouble() ;
    System.out.prin t("\nEnter Lower Estimate of x: ");
    lower = sc.nextDouble() ;



    while(err2>err)
    {
    System.out.prin t("\nIteratio n Number: " + iter);
    x = (upper+lower)/2;
    System.out.prin t("\nImproved Estimate: " + x);
    for(int i=1;i<arr.lengt h;i++)
    {
    temp1 += arr[i-1]*Math.pow(upper ,arr[i]);
    temp2 += arr[i-1]*Math.pow(lower ,arr[i]);
    temp3 += arr[i-1]*Math.pow(x,arr[i]);
    i++;
    }

    System.out.prin t("\nValue of the function at the upper estimate: " + temp1);
    System.out.prin t("\nValue of the function at the lower estimate: " + temp2);
    System.out.prin t("\nValue of the function at the improved estimate: " + temp3);

    temp4 = temp1*temp3;
    temp5 = temp2*temp3;

    System.out.prin t("\nProduct of the value function at the upper estimate & improved estimate : " + temp4);
    System.out.prin t("\nProduct of the value function at the lower estimate & improved estimate : " + temp5);

    if(temp4<0)
    {
    err2 = (upper-x)/upper;
    if(err2<0)
    {
    err2 = -1*err2;
    }
    System.out.prin t("\nRelative Error: " + err2);
    if(err2>err)
    {
    upper = x;
    }
    }
    if(temp5<0)
    {
    err2 = (lower-x)/lower;
    if(err2<0)
    {
    err2 = -1*err2;
    }
    System.out.prin t("\nRelative Error: " + err2);
    if(err2>err)
    {
    lower = x;
    }
    }
    iter++;
    }
    //System.out.prin t("Relative Error: " + err2);
    }
    }
Working...