Integral with the Parallel Patterns Library

Played a bit with PPL this week-end. This helped me understand quite a bit more than what’s in the documentation thanks to the Visual Studio 2010’s Parallel Tasks and Parallel Stacks windows:

#define _WIN32_WINNT 0x0601

#include <windows.h>

#include <ppl.h>

#include <iostream>

#include <exception>

using namespace std;

using namespace Concurrency;


double Integrand(double x) {

   return 3 * x * x;



template <typename FN>

double Integrate(FN fn,double from, double to, double dx) {

   if (from >= to)

      throw invalid_argument("’from’ must be smaller than ‘to’");


   if (dx <= 0)

      throw invalid_argument("’dx’ must be greater than 0");


   auto steps = static_cast<size_t>((to – from) / dx);


   if (!steps)

      throw underflow_error("’dx’ is too big or the interval [‘from’, ‘to’] is too small");


   combinable<double> integral;

   from += dx / 2; // Let’s position ourself at the middle of the rectangle between [from, from + dx]

   parallel_for(size_t(0), steps, [&] (int partition) {

      integral.local() += dx * fn(from + dx * partition) ;



   return integral.combine(plus<double>());



int wmain() {

   auto from = 0.0;

   auto to = 5.0;

   auto dx = 0.1;

   wcout << L"Integral of 3*X^2 between " << from << L" and " << to << L" is " << Integrate(Integrand, from, to, dx) << endl;

   return 0;


This entry was posted in Computers and Internet. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s