require bigdecimal class ExtrFinder def initialize eps fprime eps eps

 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
require 'bigdecimal'
class ExtrFinder
def initialize(f,a,b,eps, fprime)
@f = f
@a = a
@b = b
@eps = eps
@fprime = fprime
end
def dixitom
@iter = 0
while (@b - @a) > 2 * @eps
@iter +=1
@c = (@a + @b)/BigDecimal("2.0")
if @f.call(@a) * @f.call(@c) > 0
@a = @c
else
@b = @c
end
end
end
def newton(x0)
@iter = 0
@x0 = x0
@x1 = x0
begin
@x0 = @x1
@iter += 1
@y = @f.call(@x0)
@yprime = @fprime.call(@x0)
@x1 = @x0 - @y/@yprime
end while @f.call(@x1) * @f.call(@x1 + @eps * self.sign(@f.call(@x1) - @f.call(@x0))) < 0
end
def sign(x)
#print "x in sign: ", x, "\n"
#print "sign: ", x/x.abs, "\n"
if x == 0
return 0
else return x/x.abs
end
end
def printresultd
print "dih: ", "iter: ", @iter," zer:" , ((@a + @b)/2.0), "\n"
end
def printresultn
print "new: ", "iter: ", @iter," zer:" ,( @x1 + @eps * self.sign(@f.call(@x1) - @f.call(@x0))/2.0 ) , "\n"
end
end
func = Proc.new {|x| (x - 1)*(x - 2)*(x - 3)}
fprime = Proc.new {|x| 3 * x * x - 12 * x + 11}
counter = ExtrFinder.new(func, BigDecimal("0.5"), BigDecimal("1.5"), BigDecimal("0.1"),fprime)
counter.dixitom
counter.printresultd
counter = ExtrFinder.new(func, BigDecimal("1.5"), BigDecimal("2.5"), BigDecimal("0.1"),fprime)
counter.dixitom
counter.printresultd
counter = ExtrFinder.new(func, BigDecimal("2.5"), BigDecimal("3.5"), BigDecimal("0.1"),fprime)
counter.dixitom
counter.printresultd
counter = ExtrFinder.new(func, BigDecimal("0.5"), BigDecimal("1.5"), BigDecimal("0.1"),fprime)
counter.newton(0.9)
counter.printresultn
counter = ExtrFinder.new(func, BigDecimal("1.5"), BigDecimal("2.5"), BigDecimal("0.1"),fprime)
counter.newton(1.9)
counter.printresultn
counter = ExtrFinder.new(func, BigDecimal("2.5"), BigDecimal("3.5"), BigDecimal("0.1"),fprime)
counter.newton(2.9)
counter.printresultn