/Users/lyon/j4p/src/math/RootFinder.java

1    package math; 
2     
3    interface Function { 
4      public double f(double x); 
5    } 
6     
7    class AnnuityFunction implements Function { 
8      public double f(double r) { 
9        return (12 * 250 / r) * Math.pow((1 + r / 12), 240) - 1 - 250000; 
10     } 
11   } 
12    
13   public class RootFinder { 
14    
15     public static void main(String args[]) { 
16       double i = bisection(0.1, 0.2, new AnnuityFunction()); 
17       System.out.println("i=" + i); 
18     } 
19    
20     public static double bisection(double a, double b, Function fi) { 
21       double m = 0.0; 
22       int trys = 0; 
23       while (isNotCloseEnough(a, b)) { 
24         m = (a + b) / 2; 
25    
26         // Check to see if root was hit at midpoint 
27         if (fi.f(m) == 0) break; 
28         if (fi.f(a) * fi.f(m) < 0) 
29           b = m; 
30         else 
31           a = m; 
32         trys++; 
33       } // End while 
34       System.out.println("done in:" + trys + " trys"); 
35       return m; 
36     } 
37    
38     public static final double falsePosition(double a, double b, Function fi) { 
39       double xold = a, 
40           xn = b, 
41           m = 0.0; 
42    
43       while (isNotCloseEnough(a, b)) { 
44         xold = xn; 
45         m = (a * fi.f(b) - b * fi.f(a)) / (deltaF(b, a, fi)); 
46    
47         // Check to see if root was hit 
48         if (fi.f(m) == 0) break; 
49         if (fi.f(a) * fi.f(m) < 0) 
50           b = m; 
51         else 
52           a = m; 
53    
54         xn = m; 
55       } 
56       return m; 
57     } // End False Position 
58    
59     private static final double deltaF(double b, double a, Function fi) { 
60       return fi.f(b) - fi.f(a); 
61     } 
62    
63    
64     public static final double secant(double a, double b, Function fi) { 
65       double m = 0.0; 
66    
67       while (isNotCloseEnough(a, b)) { 
68         m = (a * fi.f(b) - b * fi.f(a)) / (deltaF(b, a, fi)); 
69         a = b; 
70         b = m; 
71       } 
72       return m; 
73     } // End Secant 
74    
75     private static final boolean isNotCloseEnough(double a, double b) { 
76       double stopCriterion = 0.0000001; 
77       return Math.abs(a - b) > stopCriterion; 
78     } 
79    
80    
81   } 
82