old ruby

  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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
class Funct
def initialize(f,a,b,n)
@f = f;
@a = a;
@b = b;
@n =n;
@h = (@b - @a)/@n;
@xmas = [];
v = @a;
for i in 0..(@n-1)
@xmas[i] = v;
v += h;
end
end
def f
@f
end
def a
@a
end
def b
@b
end
def n
@n
end
def h
@h
end
def xmas
@xmas
end
end
class Midrect
def count(f)
@integr = 0.0;
for i in 1..(f.n - 1)
@integr +=f.f.call((f.xmas[i-1] + f.xmas[i]) / 2.0);
end
@integr *= f.h;
end
def integr
@integr
end
end
class Trapec
def count(f)
@integr = 0.0;
for i in 1..(f.n - 2)
@integr +=f.f.call(f.xmas[i]);
end
@integr += (f.f.call(f.xmas[0]) + f.f.call(f.xmas[f.n - 1])) / 2.0;
@integr *= f.h;
#print @integr,"-------\n";
end
def integr
@integr
end
end
class Simps
def count(f)
#print "simps";
@integr = 0.0;
@integr1 = 0.0;
for i in 1..(f.n - 2)
@integr1 +=f.f.call(f.xmas[i]);
end
@integr1 *= 2;
@integr2 = 0.0;
for i in 1..(f.n - 1)
@integr2 +=f.f.call( (f.xmas[i-1] + f.xmas[i])/2.0 );
end
@integr2 *= 4;
@integr += @integr1 + @integr2;
@integr += f.f.call(f.xmas[0]);
@integr += f.f.call(f.xmas[f.n - 1]);
@integr *= f.h/6.0;
#print @integr,"-------\n";
end
def integr
@integr
end
end
class Precintegr
def initialize(prec)
@prec = prec;
end
def countwithprec(fun, a, b, integ)
@n = 2;
oldfun = Funct.new(fun, a, b, @n);
newfun = Funct.new(fun, a, b, @n*2);
integ.count(oldfun);
oldintegr = integ.integr;
integ.count(newfun);
@integr = integ.integr;
diff = (integr - oldintegr).abs()/3.0;
while (diff > @prec)
@n *= 2;
oldfun = Funct.new(fun, a, b, @n);
newfun = Funct.new(fun, a, b, @n*2);
integ.count(oldfun);
oldintegr = integ.integr;
integ.count(newfun);
@integr = integ.integr;
diff = (integr - oldintegr).abs()/3.0;
end
end
def integr
@integr
end
def n
@n
end
end
pr = Precintegr.new(0.0001);
fun = Proc.new {|x| Math.exp(x)};
integrmidrect = Midrect.new();
pr.countwithprec(fun, 0.0, 1.0, integrmidrect);
print pr.integr,"\n",pr.n,"\n";
fun = Proc.new {|x| Math.exp(x)};
integrtrapec = Trapec.new();
pr.countwithprec(fun, 0.0, 1.0, integrtrapec);
print pr.integr,"\n",pr.n,"\n";
fun = Proc.new {|x| Math.exp(x)};
integrsimps = Simps.new();
pr.countwithprec(fun, 0.0, 1.0, integrsimps);
print pr.integr,"\n",pr.n,"\n";