1
2
3
4
5
6public
7class Interpolation
8 extends SearchZero
9{
10
11
12
13
14
15 public
16 Interpolation() {
17 super();
18 }
19
20 public
21 Interpolation(double precision) {
22 super(precision);
23 }
24
25
26
27 public
28 double searchZero(double x1,
29 double x2,
30 RealFunction f)
31 throws NoZeroFoundException {
32 double y1 = f.at(x1);
33 noOfCalls = 1;
34
35 if ( Math.abs(y1) < precision )
36 return
37 x1;
38
39 double y2 = f.at(x2);
40 noOfCalls = 2;
41
42 if ( Math.abs(y2) < precision )
43 return
44 x2;
45
46 if ( (y1 >= 0) == (y2 >= 0) )
47 throw
48 new NoZeroFoundException(
49 "function values with equal signs: "
50 + "f.at(" + x1 + ") = " + y1 + ", "
51 + "f.at(" + x2 + ") = " + y2 );
52
53 while ( true ) {
54
55 double x12 = x1 - y1 * (x2 - x1) / (y2 - y1);
56
57 double y12 = f.at(x12);
58
59 ++noOfCalls;
60
61 if ( Math.abs(y12) < precision ) {
62 return
63 x12;
64 }
65
66 if ( (y1 >= 0) == (y12 >= 0) ) {
67 x1 = x12;
68 y1 = y12;
69 } else {
70 x2 = x12;
71 y2 = y12;
72 }
73
74 }
75 }
76
77
78
79 public
80 String toString() {
81 return
82 "Interpolation with precision " + precision;
83 }
84}
85