Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Table of Contents
minLevel2
maxLevel6
outlinefalse
styledecimal
typelist
printabletrue

...

Code Block
languagec
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <omp.h>

long long monte_carlo_pi(long long num_samples, int num_threads) {
    long long inside_circle = 0;
    #pragma omp parallel num_threads(num_threads)
    {
        unsigned int seed = 1234 + omp_get_thread_num();  // Unique seed for each thread
        long long local_count = 0;

        #pragma omp for
        for (long long i = 0; i < num_samples; i++) {
            double x = (double)rand_r(&seed) / RAND_MAX;
            double y = (double)rand_r(&seed) / RAND_MAX;
            if (x * x + y * y <= 1.0) {
                local_count++;
            }
        }

        #pragma omp atomic
        inside_circle += local_count;
    }
    return inside_circle;
}

int main(int argc, char *argv[]) {
    if (argc != 3) {
        printf("Usage: %s <num_samples> <num_threads>\n", argv[0]);
        return 1;
    }
     long long num_samples = atoll(argv[1]);  // Number of random points
    int num_threads = atoi(argv[2]);         // Number of OpenMP threads
     double start_time = omp_get_wtime();
    long long inside_circle = monte_carlo_pi(num_samples, num_threads);
    double end_time = omp_get_wtime();
     double pi_approx = 4.0 * (double)inside_circle / num_samples;

    printf("Approximated π: %.15f\n", pi_approx);
    printf("Error: %.15f\n", fabs(pi_approx - 3.141592653589793));
    printf("Execution Time: %.6f seconds\n", end_time - start_time);

    return 0;
}

Save this code into a file code.c and compile using a command

...

Computational jobs on the AI cluster are managed with a SLURM job manager. We provide an in-depth tutorial on how to use SLURM <placeholder>, but some basic examples that are immediately applicable on the AI cluster will be discussed in this section.

Important notice:

Warning

Do not run computations on login nodes

...