vidath007
vidath007

Reputation: 21

Why does this code which calculates Pi value using openmp gives a slightly different answer(the last few floating points) each time?

This is my solution using openmp which i used to parallelize the code which calculates Pi. The floating point value of Pi changes each time this is executed. Could someone explain why?

#include <stdio.h>
#include <stdlib.h>
#include <omp.h>

#define THREAD_NUM 20

static long num_steps = 100000;
double step;

int main(){

    int i;
    double x; 
    double pi;
    double sum = 0.0;
    double t1 = 0.0;
    double t2 = 0.0;

    step = 1.0/(double) num_steps;
    omp_set_num_threads(THREAD_NUM);
    t1 = omp_get_wtime();

    #pragma omp parallel
    {
        double p_sum = 0.0;

        #pragma omp for
        for(i=0; i<num_steps; i++){
    
            x = (i+0.5)*step;
            p_sum = p_sum + 4.0/(1.0+x*x);
        }

        #pragma omp atomic
        sum += p_sum;
    }

    t2 = omp_get_wtime();
    pi = step*sum;

    printf("value of pi = %lf\n", pi);
    printf("time = %lf ms\n", (t2-t1)*1000);
}

Upvotes: 1

Views: 104

Answers (2)

vidath007
vidath007

Reputation: 21

As @Gilles pointed out in the comments under the question, the problem was with the x variable which was declared as a shared variable. it should be declared as a private variable.

...

#pragma omp parallel
    {
        double x;
        double p_sum = 0.0;

        #pragma omp for
        for(i=0; i<num_steps; i++){

...

Upvotes: 1

Peter
Peter

Reputation: 3135

Floating point addition is neither associative nor commutative! This means that the exact value you obtain depends on the order in which the components of p_sum/sum are added up. To understand precisely why you have to understand how floating point addition works in practice. I would recommend reading What Every Computer Scientist should Know About Floating-Point Arithmetic.

Upvotes: 3

Related Questions