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";