# calcmet

 ``` 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 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120``` ```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; for i in 1 .. n integr += 4 * @f.call(@a + h * (i - 0.5)); end for i in 1 .. (n - 1) integr += 2 * @f.call(@a + h * i); end (integr + @f.call(@a) + @f.call(@b)) * h / 6.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"; ```