Newton method
x1 = x0 - (f(x0)/f'(x0))
x2 = x1 - (f(x1)/f'(x1))
.
.
.
xn = xn-1 - (f(xn-1)/f'(xn-1))
Here x0 shows initial root prediction. f'(x) represents the derivative of the f(x) function. The program will get the values a, b, c, n, x0 from the user. The program will find the roots of the axx b*x c = 0 equation. The program will print xn value.
I defined a,b,c and x0 as double data type. I defined value of n as int data type. How can I define for loop or while loop related to Newton method ?
Here I took values from user via Scanner class:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("a = ");
double a = sc.nextDouble();
System.out.print("b = ");
double b = sc.nextDouble();
System.out.print("c = ");
double c = sc.nextDouble();
System.out.print("n = ");
int n = sc.nextInt();
System.out.print("x0 = ");
double x0 = sc.nextInt();
}
Then I defined methods as function and derivativeOfFunction method. In main method how can I call functions or do I need to create for or while loop in main method ? What can I do ?
public static double function(double a, double b, double c, double x) {
return (a * Math.pow(x, 2)) (b * x) c;
}
public static double derivativeOfFunction(double a, double b, double x) {
return 2 * a * x b;
}
CodePudding user response:
The newton formula is
x1 = x0 - (f(x0)/f'(x0))
When you insert your functions you get the following code fragment:
double x1 = x0 - function(a, b, c, x0) / derivativeOfFunction(a, b, x0);
You could just wrap this in a for-loop:
for (int i = 1; i <= n; i ) {
double x1 = x0 - function(a, b, c, x0) / derivativeOfFunction(a, b, x0);
}
but this would calculate n times the value of x1 and the result would be lost after the for loop terminates.
So you need a variable that is initialized with x0 and modified n times:
double xi = 0;
for (int i = 1; i <= n; i ) {
xi = xi - function(a, b, c, xi) / derivativeOfFunction(a, b, xi);
}
System.out.println("xn=" xi);
and then the value of xn is the value of xi after n iterations.
Note that you could even shorten the body of the for loop to
double xi = 0;
for (int i = 1; i <= n; i ) {
xi -= function(a, b, c, xi) / derivativeOfFunction(a, b, xi);
}
System.out.println("xn=" xi);