Do more. Code less. Free software for GPU computing.
<scroll to top>

examples/pi/pi.cpp

/*
   monte-carlo estimation of PI

   algorithm:
   - generate random (x,y) samples uniformly
   - count what percent fell inside (top quarter) of unit circle
*/

#include <stdio.h>
#include <arrayfire.h>
using namespace af;

// generate millions of random samples
static int samples = 20e6;

/* Self-contained code to run GPU and CPU estimates of PI.  Note that
   each is generating its own random values, so the estimates of PI
   will differ. */
static double pi_gpu()
{
    array x = randu(samples,f32), y = randu(samples,f32);
    return 4.0 * sum<float>((mul(x, x) + mul(y, y)) < 1) / samples;
}

static double pi_cpu()
{
    int count = 0;
    for (int i = 0; i < samples; ++i) {
        float x = float(rand()) / RAND_MAX;
        float y = float(rand()) / RAND_MAX;
        if (sqrt(x*x + y*y) < 1)
            count++;
    }
    return 4.0 * count / samples;
}



// void wrappers for timeit()
static void gpu_wrapper() { pi_gpu(); }
static void cpu_wrapper() { pi_cpu(); }


int main(int argc, char ** argv)
{
    try {
        printf("gpu:  %.5f seconds to estimate  pi = %.5f\n", timeit(gpu_wrapper), pi_gpu());
        printf("cpu:  %.5f seconds to estimate  pi = %.5f\n", timeit(cpu_wrapper), pi_cpu());
    } catch (exception& e) {
        fprintf(stderr, "%s\n", e.what());
    }

    #ifdef WIN32 // pause in Windows
    if (!(argc == 2 && argv[1][0] == '-')) {
        printf("hit [enter]...");
        getchar();
    }
    #endif
    return 0;
}
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Defines