Saturday, April 5, 2014

Java Program to Implement bisection Method

import java.util.Scanner;

public class Bisection {

    public static double f(double x) {    // start of the method f
        double temp = Math.pow(x, 10) - 1;
        return temp;
    }// end of the method f

    public static void main(String args[]) {
        Scanner input = new Scanner(System.in);
        double x = 0;

        System.out.println("enter X (lower):");
        double a = input.nextDouble();

        System.out.println("enter X (upper):");
        double b = input.nextDouble();

        System.out.println("enter max iteration number:");
        int n = input.nextInt();
        int i;
        for (i = 1; i <= n; i++) { // for loop starts
            double temp = x;
            float error;
            x = (a + b) / 2;
            error = Math.abs((float) (((x - temp) / x) * 100));
            System.out.println("Iteration:" + i + "\ta=" + a + "\tb=" + b + "\tRoot:" + x + "\terror:" + error + "%");

            if (f(x) * f(a) < 0) {
                b = x;
            }

            if (f(x) * f(a) > 0) {
                a = x;
            }

            if (f(x) * f(a) == 0) {
                System.out.println("the root equals: " + x);
                break;
            }
           
        }// ends for loop here

        if (i > n)
         {
            System.out.println("max iteration exceeded:");

         }
    }
}

No comments:

Post a Comment