1
2
3
4
5
6public
7class IntervallNesting
8 extends SearchZero
9{
10
11
12
13
14
15 public
16 IntervallNesting() {
17 super();
18 }
19
20 public
21 IntervallNesting(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 double x12 = (x2 + x1) / 2.0;
55 double y12 = f.at(x12);
56 ++noOfCalls;
57
58 if ( Math.abs(y12) < precision ) {
59 return
60 x12;
61 }
62
63 if ( (y1 >= 0) == (y12 >= 0) ) {
64 x1 = x12;
65 y1 = y12;
66 } else {
67 x2 = x12;
68 y2 = y12;
69 }
70
71 }
72 }
73
74
75
76 public
77 String toString() {
78 return
79 "IntervallNesting with precision " + precision;
80 }
81}
82