class IntegrwithPrec def initialize(f, a, b, precval, fixeps, min, max) @f = f; @a = a; @b = b; @precval = precval; @fixeps = fixeps; @min = min; @max = max; end def midrect(n) integr = 0.0; h = (@b - @a) / n; for i in 1 .. n integr += @f.call(@a + h * (i - 0.5)); end integr * h end def trapets(n) integr = 0.0; h = (@b - @a) / n; for i in 1 .. (n - 1) integr += @f.call(@a + h * i); end (integr + (@f.call(@a) + @f.call(@b))/2) * h end def simpsons(n) integr = 0.0; h = (@b - @a) / n; i = 1; while (i < n) integr += @f.call(@a + h * (i - 1)) + 4 * @f.call(@a + h * i) + @f.call(@a + h * (i + 1)); i+=2; end integr * h / 3.0 end def mk(n) prng = Random.new; k = 0; x = 0.0; y = 0.0; for i in 0 .. (n - 1) x = prng.rand(@a .. @b); y = prng.rand(@min .. @max); if y < @f.call(x) k += 1; end end (@b - @a) * (@max - @min) * k / n end end class Myclass def midrectprec() funexp = Proc.new {|x| Math.exp(x)}; calcexp = IntegrwithPrec.new(funexp, 0.0, 1.0, Math.exp(1) - 1, 0.001, 0, funexp.call(1)); count = 2; \$I1 = 0.0; \$I2 = calcexp.midrect(count); begin count *= 2; \$I1 = \$I2; \$I2 = calcexp.midrect(count); end until ((\$I1 - \$I2).abs() / 3) < 0.001; superI = (4 * \$I2 - \$I1) / 3; print "средние прямоугольники ", count, " ", \$I2, " ", superI, " ", (superI - Math.exp(1) + 1).abs(), "\n"; end def trapetsprec() funexp = Proc.new {|x| Math.exp(x)}; calcexp = IntegrwithPrec.new(funexp, 0.0, 1.0, Math.exp(1) - 1, 0.001, 0, funexp.call(1)); count = 2; \$I1 = 0.0; \$I2 = calcexp.trapets(count); begin count *= 2; \$I1 = \$I2; \$I2 = calcexp.trapets(count); end until ((\$I1 - \$I2).abs() / 3) < 0.001; superI = (4 * \$I2 - \$I1) / 3; print "трапеций ", count, " ", \$I2, " ", superI, " ", (superI - Math.exp(1) + 1).abs(), "\n"; end def simpsonsprec() funexp = Proc.new {|x| Math.exp(x)}; calcexp = IntegrwithPrec.new(funexp, 0.0, 1.0, Math.exp(1) - 1, 0.001, 0, funexp.call(1)); count = 2; \$I1 = 0.0; \$I2 = calcexp.simpsons(count); begin count *= 2; \$I1 = \$I2; \$I2 = calcexp.simpsons(count); end until ((\$I1 - \$I2).abs() / 15) < 0.001; superI = (16 * \$I2 - \$I1) / 15; print "симпсона ", count, " ", \$I2, " ", superI, " ", (superI - Math.exp(1) + 1).abs(), "\n"; end end my = Myclass.new(); print "eps = 0.001\n"; print Math.exp(1) - 1, "\n"; my.midrectprec(); my.trapetsprec(); my.simpsonsprec(); funexp = Proc.new {|x| Math.exp(x)}; calcexp = IntegrwithPrec.new(funexp, 0.0, 1.0, Math.exp(1) - 1, 0.001, 0, funexp.call(1)); integr = 0.0; integr = calcexp.mk(500); print "монте-карло ", integr, " ", (integr - Math.exp(1) + 1).abs(), "\n";