// // integrater.h // mc_electron // // Created by Christian Reiling on 14.11.19. // Copyright © 2019 Christian Reiling. All rights reserved. // #ifndef integrater_h #define integrater_h // Integrater from https://rosettacode.org/wiki/Numerical_integration#C.2B.2B // the integration routine template double integrate(F f, Float a, Float b, int steps, Method m) { double s = 0; double h = (b-a)/steps; for (int i = 0; i < steps; ++i) s += m(f, a + h*i, h); return h*s; } // methods class rectangular { public: enum position_type { left, middle, right }; rectangular(position_type pos): position(pos) {} template double operator()(F f, Float x, Float h) const { switch(position) { case left: return f(x); case middle: return f(x+h/2); case right: return f(x+h); } } private: const position_type position; }; class trapezium { public: template double operator()(F f, Float x, Float h) const { return (f(x) + f(x+h))/2; } }; class simpson { public: template double operator()(F f, Float x, Float h) const { return (f(x) + 4*f(x+h/2) + f(x+h))/6; } }; template double double_simpson_integrate(F f, Double xmin, Double xmax, Double ymin, Double ymax, int nx, int ny) { // Adapted from https://www.geeksforgeeks.org/program-to-calculate-double-integration/ // and http://www.physics.usyd.edu.au/teach_res/mp/doc/math_integration_2D.pdf // and http://mathfaculty.fullerton.edu/mathews/n2003/SimpsonsRule2DMod.html // Make number of steps even if (nx % 2 != 0) { nx += 1; } if (ny % 2 != 0) { ny += 1; } // Calculating the step sizes Double xsteps = (xmax - xmin)/(nx-1); Double ysteps = (ymax - ymin)/(ny-1); // Lambda for calculating function value in respect to x and y bins auto f_bin = [&](int ix, int iy) { return f(xmin + ix * xsteps, ymin + iy * ysteps); }; // Lambda for calculating the integral over y for a ix bin auto x_integral = [&](int ix) { Double res = 0; for (int iy = 0; iy < ny; iy++) { if (iy == 0 || iy == ny - 1) res += f_bin(ix, iy); else if (iy % 2 == 0) res += 2 * f_bin(ix, iy); else res += 4 * f_bin(ix, iy); } res *= (ysteps / 3); return res; }; // Calculating the final integral value over x Double res = 0; for (int ix = 0; ix < nx; ix++) { if (ix == 0 || ix == nx - 1) res += x_integral(ix); else if (ix % 2 == 0) res += 2 * x_integral(ix); else res += 4 * x_integral(ix); } res *= (xsteps / 3); return res; } #endif /* integrater_h */