Newton-Raphson Method in Java

user4227114 picture user4227114 · Mar 6, 2015 · Viewed 8.5k times · Source

I am making a program to apply Newton-Raphson method in Java with an equation:

f(x) = 3x - e^x + sin(x)

And

g(x) = f'(x) = 3- e^x + cos (x)

The problem is when I tried to solve the equation in a paper to reach an error less than (0.5%)
I got:

          Xn                             |           Error

        Xo = 2                        |    ------------------------

  X1 = 1.900158400           |            5.254%

  X2 = 1.89012709             |            0.5307%

But when I made the program in Java it does not reach the last line which is the required error
(Ex: X2 = 1.89012709)
It only displays the first line which is the first step which is
(X1 = 1.900158400)

My Java code is:

package newton.raphson.method;

public class NewtonRaphsonMethod {


          // let f be a function defined as f(x) = 3x - e^x + sin(x)

        public static double f (double x){

            return (3*x-(Math.pow(Math.E, x))+Math.sin(x));
        }

        // let g be a function defined as g(x) = f'(x) = 3- e^x + cos (x)


     public static double g (double x){

            return (3-(Math.pow(Math.E, x))+Math.cos(x));
        }


          public static double NewtonRaphson (){
              int iterations_number=0;
              boolean cont = true;
            double x0 , x1, Error=5000;
            x0 =2;
            x1=0;

            while (cont){
            x1 = x0 - (f(x0)/g(x0));
            Error = (Math.abs(x1-x0)/x1)*100;
            iterations_number++;
            if (f(x1)<=0.05){
            cont = false;
            System.out.println("The Program did it in "+iterations_number+" Step(s)");
            System.out.println("The root is: "+ x1);
             System.out.println("The Error is: "+(Math.abs(x1-x0)/x1)*100+"%");
            }
            }

            return x1;
        }

    public static void main(String[] args) {
         NewtonRaphson();

    }
}


And the output is:

The Program did it in 1 Step(s)
The root is: 1.9001584993293807
The Error is: 5.254377500921955%

Answer

The Gilbert Arenas Dagger picture The Gilbert Arenas Dagger · Mar 6, 2015

The reason that your code is never "hitting the last line", presumably you are referring to the return statement in your NewtonRhapson() method, is that it is in an infinite loop. Each iteration of the loop is identical to the last. You set x0 outside of the loop, then never set it again. Given that the rest of the values / calculations in your loop are derived from x0 you are getting the same results over and over again.