экстремум вычисл мет

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