3 * Calculates PI using integration
4 * Compares results obtained with float, double, and Real.
7 #include <cmath> // for PI
8 #include <ctime> // for performance measurements
10 /** Function to integrate
13 template <class T> T f(const T & x)
15 // Use reference because Real might get big
16 return T(4.0) / (T(1.0) + x*x);
20 * Integrate f using the simpson rule
22 template <class T> T Integrate(T(*f)(const T&), const T & xmin, const T & xmax, uint64_t intervals)
25 T dx = (xmax - xmin) / T(intervals);
30 for (i = 1; i < intervals-1; i+=2)
31 odd += f(xmin + dx*T(i));
32 for (i = 2; i < intervals-1; i+=2)
33 even += f(xmin + dx*T(i));
35 sum = (f(xmin) + T(4.0)*odd + T(2.0)*even + f(xmin+T(intervals)*dx))*dx / T(3.0);
40 #define MAX_INTERVALS 1e9
45 int main(int argc, char ** argv)
47 printf("# intervals\terror_float\tclock_float\terror_double\tclock_double\terror_real\tclock_real\n");
48 for (uint64_t intervals = 1; intervals < (uint64_t)(MAX_INTERVALS); intervals*=10)
50 clock_t start = clock();
51 float error_float = Integrate<float>(f<float>, 0.0, 1.0, intervals) - (float)(M_PI);
52 clock_t clock_float = clock() - start;
54 double error_double = Integrate<double>(f<double>, 0.0, 1.0, intervals) - (double)(M_PI);
55 clock_t clock_double = clock() - start;
57 Real error_real = Integrate<Real>(f<Real>, 0.0, 1.0, intervals) - Real(M_PI);
58 clock_t clock_real = clock() - start;
60 printf("%lu\t%.30f\t%li\t%.30f\t%li\t%.30f\t%li\n", intervals, error_float, clock_float, error_double, clock_double, Float(error_real), clock_real);