Reputation: 11
I have created a program that calculates the Newton Raphson method. I am trying to edit it so it will calculate Newton Rapshon but instead of using f'(x)
I am using the Finite difference formula which is:
f(x-h)-f(h)/h where h is always more than 0.
I have the program working but when the user inputs a value the prgram does not calculate it. It keeps asking for a value. In previous cases the value would not output. Apologies about the long explanation.
public class NewtonRaphsonDevAp {
public static double func(double x) {
return (5 * Math.pow(x, 2) - 6 * Math.pow(x, 3) + 2 * x - 3);
}
public static double derivative_approx(double x, double h) {
return ((func(x - h) - func(h)) / h);
}
public static double NewtonRaphsonDevAp() {
boolean cont = true;
double x, h, x1;
Scanner scan = new Scanner(System. in );
x = scan.nextDouble();
h = 0.01;
x1 = 0;
while (cont) {
x1 = x - (func(x) / derivative_approx(x, h));
if (func(x1) <= 0.000001) {
cont = false;
System.out.println("f(x)= " + func(x));
System.out.println("g(x)= " + derivative_approx(x, h));
System.out.println("The root is " + x1);
}
}
return x1;
}
public static void main(String[] args) {
NewtonRaphsonDevAp();
}
}
Upvotes: 1
Views: 146
Reputation: 1213
while(cont) {
x1 = x - (func(x) / derivative_approx(x,h));
System.out.printf("x1 - %.7f\nfunc(x1) - %.7f\n", x1, func(x1));
if (func(x1) <= 0.000001) {
cont = false;
System.out.println("f(x)= " + func(x));
System.out.println("g(x)= " + derivative_approx(x,h));
System.out.println("The root is " + x1);
}
}
When I input 3 as the number this is my output.
x1 - 2.9895287
func(x1) - 193.9408206
x1 - 2.9895287
func(x1) - 193.9408206
x1 - 2.9895287
func(x1) - 193.9408206
x1
is never being set to another number. So basically your checking if(func(x1) <= 0.000001)
on the same x1
an infinite number of times. I'd say you may be looking for.
Let x
be set to x-(func(x) / derivative_approx(x,h));
each turn, so your x1
also gets smaller on each loop.
while (cont){
x1 = x-(func(x) / derivative_approx(x,h));
if (func(x1) <= 0.000001) {
cont = false;
System.out.println("f(x)= " + func(x));
System.out.println("g(x)= " + derivative_approx(x,h));
System.out.println("The root is " + x1);
} else {
x = x1;
}
}
or ask for a new number.
while (cont){
x1 = x-(func(x) / derivative_approx(x,h));
if (func(x1) <= 0.000001){
cont = false;
System.out.println("f(x)= " + func(x));
System.out.println("g(x)= " + derivative_approx(x,h));
System.out.println("The root is " + x1);
} else {
x = scan.nextDouble();
}
}
Upvotes: 2