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