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
| namespace math {
namespace integrals {
//j'utilise _f pour les typedef de fonctions.
template <typename FROM, typename TO = FROM>
using unary_f = TO (*)(FROM x);
template <typename FROM, typename TO = FROM>
using integration_f = TO (*)(unary_f<FROM, TO>, FROM a, FROM b);
template <typename FROM, typename TO = FROM, typename D = FROM>
TO integrate(unary_f<FROM, TO> f, FROM a, FROM b, unsigned int n, integration_f<D, TO> integration) {
if (a == b || n == 0) return 0;
if (a > b) return -integrate(f, b, a, n, integration);
D dx = (b-a)/n;
TO somme = 0;
for (int i = 0; i < n; ++i) {
D that = a + i*dx;
somme += integration(f, that, that + dx);
}
return somme + integration(f, a + n*dx, b);
}
}//integrals::
}//math::
namespace math {
namespace integrals {
template <typename FROM, typename TO = FROM>
TO trapezes(unary_f<FROM, TO> f, FROM a, FROM b) {
return (b-a) * (f(a) + f(b))/2;
}
}//integrals::
}//math::
using namespace mi = math::integrals
using namespace std;
int main() {
cout << "intégrale de sinus sur [0, 4]" << mi::integrate(sin, 0, 4, 12, mi::trapezes<float>) << endl;
return 0;
} |
Partager