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.print("Enter Power of Polynomial: ");
int pow = sc.nextInt();
System.out.print("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.print("\nEnter Coefficient: ");
arr[j-1] = sc.nextInt();
System.out.print("Enter Exponent: ");
arr[j] = sc.nextInt();
j++;
}
System.out.print("\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.print("\nEnter Upper Estimate of x: ");
upper = sc.nextDouble();
System.out.print("\nEnter Lower Estimate of x: ");
lower = sc.nextDouble();
while(err2>err)
{
System.out.print("\nIteration Number: " + iter);
x = (upper+lower)/2;
System.out.print("\nImproved Estimate: " + x);
for(int i=1;i<arr.length;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.print("\nValue of the function at the upper estimate: " + temp1);
System.out.print("\nValue of the function at the lower estimate: " + temp2);
System.out.print("\nValue of the function at the improved estimate: " + temp3);
temp4 = temp1*temp3;
temp5 = temp2*temp3;
System.out.print("\nProduct of the value function at the upper estimate & improved estimate : " + temp4);
System.out.print("\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.print("\nRelative Error: " + err2);
if(err2>err)
{
upper = x;
}
}
if(temp5<0)
{
err2 = (lower-x)/lower;
if(err2<0)
{
err2 = -1*err2;
}
System.out.print("\nRelative Error: " + err2);
if(err2>err)
{
lower = x;
}
}
iter++;
}
//System.out.print("Relative Error: " + err2);
}
}