All pastes #801563 Raw Edit

Numeric Integration: Trapeze and

public text v1 · immutable
#801563 ·published 2007-11-29 11:59 UTC
rendered paste body
program Integral;

type
	TFunc = function(x : Real) : Real;

function trapeze(a, b : Real; n : Integer; func : TFunc) : Real;
var
	ya, yb : Real;
	d, x, sum : Real;
begin
	ya := func(a);
	yb := func(b);
	d := (b - a) / n;
	x := a + d;
	sum := ya + yb;

	while (x < b) do begin
		sum := sum + 2 * func(x);
		x := x + d;
	end;

	trapeze := d * sum / 2;
end;

function simpson(a, b : Real; n : Integer; func : TFunc) : Real;
var
	ya, yb, y : Real;
	d, sum : Real;
	i : Integer;
begin
	ya := func(a);
	yb := func(b);
	d := (b - a) / (2 * n);
	sum := ya + yb;

	i := 1;
	while (i < 2 * n) do begin
		y := func(a + d * i);
		i := i + 1;

		if odd(i) then
			sum := sum + 4 * y
		else
			sum := sum + 2 * y;
	end;

	simpson := sum * d / 3;
end;

function func(x : Real) : Real;
begin
	func := x*x*x*x + x;
end;

var
	t, s : Real;
	n : Integer;

begin
	Write('vvedite kolichestvo razbieniy: ');
	ReadLn(n);
	t := trapeze(0, 1, n, func());
	WriteLn('trapeze method: ', t);
	s := simpson(0, 1, n, func());
	WriteLn('simpson method: ', s);
end.