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