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%