Skip to content
Snippets Groups Projects
taylor.c 999 B
Newer Older
Bruce Cowan's avatar
Bruce Cowan committed
#include <stdio.h>

#include <omp.h>

static const size_t NUM_STEPS = 1e9;

static double
e_func (size_t n)
{
	double e = 1;
	double factorial = 1;

	printf ("e started\n");

	#pragma omp parallel for shared(factorial) reduction(+:e)
	for (size_t i = 1; i < n; i++)
	{
		factorial *= i;
		e += 1.0 / factorial;
	}

	return e;
}

static double
pi_func (size_t n)
{
	double pi = 0;

	printf ("pi started\n");

	for (size_t i = 0; i < n; i++)
	{
		pi += 1.0 / (i * 4.0 + 1.0);
		pi -= 1.0 / (i * 4.0 + 3.0);
	}

	pi *= 4.0;

	return pi;
}

int 
main (void)
{
	#pragma omp parallel sections
	{
		#pragma omp section
		{
			double start = omp_get_wtime ();
			double e = e_func (NUM_STEPS);
			double stop = omp_get_wtime ();
			printf ("e = %lf, took %.3f seconds\n", e, stop-start);
		}
		#pragma omp section
		{
			double start = omp_get_wtime ();
			double pi = pi_func (NUM_STEPS);
			double stop = omp_get_wtime ();
			printf ("pi = %lf, took %.3f seconds\n", pi, stop-start);
		}
	}

	return 0;
}