-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathNewtonRhapson2.java
More file actions
79 lines (69 loc) · 1.93 KB
/
Copy pathNewtonRhapson2.java
File metadata and controls
79 lines (69 loc) · 1.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import java.util.Scanner;
/**
* This class illustrates applies the newton rhapson method
* to find the root of a given polynomial.
* assignment 2 2018
* f(x) -> 3* Math.pow(x, 5) + Math.pow(x,3) - x - 1.0;
* f(x) -> 3x^5 + x^3 - x - 1.0
*
* f'(x) -> 15*Math.pow(x,4) + 2*x -1
* f'(x) -> 15x^4 + 2x -1.0
*
* teacher's solution
*
* @author P.Campbell
* @version today
**/
public class NewtonRhapson2 {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
int count=0;
double x0, xn, xnplus1;
System.out.print("Enter initial value for x (x sub 0):");
xn = kb.nextDouble();
x0 = xn; // needed to print
// get initial xnplus1
// needed to prime the border condition
xnplus1 = newtonRhapsonF(xn);
count++;
while (Math.abs(xn - xnplus1) >= 0.0001) {
System.out.printf("xn %.7f xnplus1 %.7f\n", xn, xnplus1);
xn = xnplus1;
xnplus1 = newtonRhapsonF(xn);
count++;
}
System.out.printf("FINAL:\n xn %.7f xnplus1 %.7f\n", xn, xnplus1);
System.out.println("\npolynomial 3x^5 +x^3 - x - 1");
System.out.println("derivative 15x^4 +3x^2 - 1");
System.out.println("\nInitial xsub0 "+x0);
System.out.println("root approx "+xnplus1);
System.out.println("iterations "+count);
} // main()
/**
* original function 3x^5 +x^3 - x - 1
*
* @param x
* @return the result of the function
**/
static double newtonRhapsonF (double x) {
return x - f(x) / fprime(x);
}
/**
* original function 3x^5 +x^3 - x - 1
*
* @param x
* @return the result of the function
**/
static double f (double x) {
return 3* Math.pow(x, 5) + Math.pow(x,3) - x - 1.0;
}
/**
* derivative of original function 3x^5 +x^3 - x - 1
* 15x^4 +2x^2 -1
* @param x
* @return the result of the function
**/
static double fprime (double x) {
return 15*Math.pow(x,4) + 2*x*x -1;
}
} // class NewtonRhapson