Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

C Programming

Name: Anonymous 2012-09-27 14:06

Hi /prog/,
I'm writing a small program in C to calculate the value of pi using the Montecarlo algorithm.
What can I do to improve it ?

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

long EVALPI(long);

#ifdef EBUG
#define DEBUG
#endif

/* README:
        you can add -DEBUG to your CFLAGS.
        Usage: ./montecarlo [number of loops] [rand seed]
        If the number of loops is not provided, it'll be asked on the command line.
        If the rand seed is not provided, it'll use the current timestamp using time() (3).
*/

int main(int argc, char **argv){
        long c, p;

        if(argc > 1){
                p = atoi(argv[1]);
        }else{
                printf("Nombre d'iterations: ");
                scanf("%ld", &p);
        }

        if(argc > 2)
                srand(atoi(argv[2]));
        else
                srand(time(NULL));

        c = EVALPI(p);
        printf("pi ~= 4*%ld/%ld ~= %f\n", c, p, (double)(c<<2)/p);
        return 0;
}

long EVALPI(long p){
        const long CENTRE = RAND_MAX >> 1;
        const long CENTRE_2 = CENTRE * CENTRE;
        long x, y, c = 0;
#ifdef DEBUG
        long old = p, foo = p/4;
#endif
        do{
                x = CENTRE - rand();
                x *= x;
                y = CENTRE - rand();
                y *= y;
                if(x+y < CENTRE_2) c++;
#ifdef DEBUG
                if(p % foo == 1) printf("%f\n", (double)(c<<2)/(old-p));
#endif
        }while(p--);

        return c;
}

Name: Anonymous 2012-09-28 4:00

There is now precisely one unaccounted for, yet predictable and fixable failure mode in your program. If you can find it I'll be impressed.

#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <errno.h>

const long long RADIUS = RAND_MAX / 2;

int main(int argc, char **argv) {
    int a;
    long i, n, s, c = 0;
    if(argc < 2) printf("Usage: ./montecarlo n [seed]\n  n -- Number of iterations.\n  seed -- Seed for the random number generator."), exit(EXIT_FAILURE);
    else errno = 0, n = strtol(argv[1], NULL, 10);
    if((errno == ERANGE && (n == LONG_MAX || n == LONG_MIN)) || (errno != 0 && n == 0)) printf("Invalid parameter n."), exit(EXIT_FAILURE);
    if(argc < 3) srand(time(NULL));
    else errno = 0, s = strtol(argv[2], NULL, 10), a = errno, srand(s);
    if((a == ERANGE && (s == LONG_MAX || s == LONG_MIN)) || (a != 0 && s == 0)) printf("Invalid seed parameter."), exit(EXIT_FAILURE);
   
    for(i = 0; i < n; i++) {
        long long dx = rand() - RADIUS;
        long long dy = rand() - RADIUS;
        if(dx * dx + dy * dy < RADIUS * RADIUS) c++;
    }
    printf("PI ~= 4 * %ld / %ld ~= %f\n", c, n, 4 * c / (double)n);
    return EXIT_SUCCESS;
}

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List