# [C] More pi and hot dogs! (but faster)

## Recommended Posts

So a while back I made this post where I approximated pi by throwing hot dogs on the floor. Back then I was only really concerned with making the program work in order to test what I had read, but it always bothered me that I had to leave the program for so long in order to throw 1 billion hot dogs. For that reason I wrote up another version in C with the sole goal of making it super fast!

This is what I came up with:

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

int main(int argc, char *argv[]){
double halfComponent, dist, intersects = 0;
int i;
time_t t;
srand((unsigned) time(&t));
for(i = 0; i<1000000000; ++i){
dist = rand()/(double)(RAND_MAX);
halfComponent = sin(rand()/(RAND_MAX/6.28318530718))/2;
if((int)(dist - halfComponent) != (int)(dist + halfComponent)){
++intersects;
}
}
printf("%f\n", (1000000000/intersects));
return 0;
}```

This program merely drops the hot dogs on the floor instead of throwing them (although there's no real difference). I used a length/distance of 1 so as to simplify some checks in the program. That allows me to check for intersections simply by seeing if the top-most and bottom-most points of the hot dog are on different sides of an integer. I originally used the floor() function in the conditional, but typecasting to an integer is faster. I eliminated as many variables as I can see how. I think this is about as fast as I'm going to get it by myself, and I can't argue too much with the results:

That's an error of ~0.00003 which is actually less than before (albeit entirely by chance), and I can hardly argue with 108 seconds.

## Create an account or sign in to comment

You need to be a member in order to leave a comment

## Create an account

Sign up for a new account in our community. It's easy!

Register a new account