usr local bin ruby -w require bigdecimal class ExtrFinder def initiali

 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
#!/usr/local/bin/ruby -w
require 'bigdecimal'
class ExtrFinder
def initialize(f,a,b,eps)
@f = f
@a = a
@b = b
@eps = eps
end
def dixitom
@iter = 0
while (@b - @a).round(5) > BigDecimal("2.0") * @eps
#print @a, " ", @b, "\n"
#print (@b - @a).round(3),"\n"
@iter +=1
@x1 = (@a + @b)/BigDecimal("2.0") - @eps
@x2 = (@a + @b)/BigDecimal("2.0") + @eps
if @f.call(@x1) > @f.call(@x2)
@a = @x1
else
@b = @x2
end
end
end
def golden
@iter = 0
phi = (BigDecimal("1.0") + Math.sqrt(BigDecimal("5.0")))/BigDecimal("2.0")
while (@b - @a).round(5) > BigDecimal("2.0") * @eps
@iter += 1
@x1 = @b - (@b - @a)/phi
@x2 = @a + (@b - @a)/phi
if @f.call(@x1) > @f.call(@x2)
@a = @x1
else
@b = @x2
end
end
end
def printresultd
print "дихотомия: ", "итераций:", @iter,"точка минимума:" , ((@a+@b)/BigDecimal("2.0")).round(3),"минимум:" , (@f.call((@a+@b)/BigDecimal("2.0"))).round(3), "\n"
end
def printresultg
print "золотое сечение: ", "итераций:", @iter,"точка минимума:" , ((@a+@b)/BigDecimal("2.0")).round(3),"минимум:" , (@f.call((@a+@b)/BigDecimal("2.0"))).round(3), "\n"
end
end
func = Proc.new {|x| (x - BigDecimal("0.3126"))**2}
counter = ExtrFinder.new(func, -BigDecimal("1.0"), BigDecimal("2.0"), BigDecimal("0.001"))
counter.dixitom
counter.printresultd
counter = ExtrFinder.new(func, -BigDecimal("1.0"), BigDecimal("2.0"), BigDecimal("0.001"))
counter.golden
counter.printresultg