C++ Bc. 30 cpp
#include <iostream>
#include <cmath>
double simpson(double (*f)(double), double a, double b, int m);
int main()
{
using namespace std;
for (int m=2; m<=8; m+=2)
{
cout << "\n a "
<< " b "
<< " simpson "
<< " chyba "
<< " m = " << m << endl;
cout << "--------------------------------------------\n";
double a=0, b=1;
for (int k=1; k<=5; k++)
{
double s = simpson(sin, a, b, m);
double e = cos(a) - cos(b);
cout.setf(ios_base::fixed, ios_base::floatfield);
cout << a << " " << b << " " << s << " ";
cout.setf(ios_base::scientific, ios_base::floatfield);
cout << e-s << endl;
a += 0.1;
b += 0.2;
}
}
}
// Priblizny vypocet urciteho integralu
double simpson(double (*f)(double), double a, double b, int m)
{
m = std::max(2, m); // m >= 2
m = (m+1)/2*2; // m musi byt sude
double h = (b - a)/m; // integracni krok
double s = f(a) + 4.0*f(a+h) + f(b);
double t = m, i = 2;
while (i < t)
{
s += 2.0*f(a + h*i);
i++;
s += 4.0*f(a + h*i);
i++;
}
return s*h/3.0;
}
a b simpson chyba m = 2
--------------------------------------------
0.000000 1.000000 0.459862 -1.644957e-04
0.100000 1.200000 0.632980 -3.335789e-04
0.200000 1.400000 0.810709 -6.092499e-04
0.300000 1.600000 0.985564 -1.027751e-03
0.400000 1.800000 1.149889 -1.625841e-03
a b simpson chyba m = 4
--------------------------------------------
0.000000 1.000000 0.459708 -1.005080e-05
0.100000 1.200000 0.632667 -2.028349e-05
0.200000 1.400000 0.810136 -3.684878e-05
0.300000 1.600000 0.984598 -6.179879e-05
0.400000 1.800000 1.148360 -9.714269e-05
a b simpson chyba m = 6
--------------------------------------------
0.000000 1.000000 0.459700 -1.977119e-06
0.100000 1.200000 0.632650 -3.986527e-06
0.200000 1.400000 0.810107 -7.235318e-06
0.300000 1.600000 0.984548 -1.212160e-05
0.400000 1.800000 1.148282 -1.903259e-05
a b simpson chyba m = 8
--------------------------------------------
0.000000 1.000000 0.459698 -6.246666e-07
0.100000 1.200000 0.632648 -1.259151e-06
0.200000 1.400000 0.810102 -2.284522e-06
0.300000 1.600000 0.984540 -3.825951e-06
0.400000 1.800000 1.148269 -6.004912e-06
[ Zpět ]