Yurttas/PL/OOL/Cplusplus/F/07/06/02/01/00/integrate.cpp

From ZCubes Wiki
Jump to navigation Jump to search
 1/*
 2   Copyright(C) 2003
 3   All Rights Reserved. Salih Yurttas, ZCubes, BitsOfCode Software Systems, Inc..
 4
 5   Permission to use, copy, modify, and distribute this
 6   software and its documentation for EDUCATIONAL purposes
 7   and without fee is hereby granted provided that this
 8   copyright notice appears in all copies.
 9
10   date   : September 1, 2003.
11   author : Salih Yurttas.
12
13   purpose : integration of f(x).
14
15   integrate.cpp
16*/
17
18
19template<class F>
20double
21integrate(const double a,
22          const double b,
23          const F& fx) {
24// evaluates approximately the integral of f(x)
25// between limits a and b,
26// using the trapezoidal rule with 8 intervals
27
28  int n = 8;
29
30  double w = (b-a) / (double) n;
31
32  double sum = (fx(a) + fx(b)) / 2.0;
33
34  for(int i=1; i<n; i++)
35    sum += fx((a + (double) i * w));
36
37  return w*sum;
38}