Skip to content

Instantly share code, notes, and snippets.

@Youka
Created September 28, 2015 02:15
Show Gist options
  • Save Youka/f008eef0eb5698e6c988 to your computer and use it in GitHub Desktop.
Save Youka/f008eef0eb5698e6c988 to your computer and use it in GitHub Desktop.
Calculate Pi
#include <stdlib.h>
#include <stdio.h>
#ifdef __SSE2__
#include <emmintrin.h>
#endif
static double calc_pi(unsigned n){
double pi, x;
#ifdef __SSE2__
const __m128d four = _mm_set1_pd(4.0);
__m128d partial;
#endif
for(pi=3.0, x=2.0; n; --n, x+=4.0)
#ifdef __SSE2__
partial = _mm_div_pd(
four,
_mm_mul_pd(
_mm_set_pd(x+2.0, x),
_mm_mul_pd(
_mm_set_pd(x+3.0, x+1.0),
_mm_set_pd(x+4.0, x+2.0)
)
)
),
pi += ((double*)(&partial))[0] - ((double*)(&partial))[1];
#else
pi += 4.0 / (x*(x+1.0)*(x+2.0)) - 4.0 / ((x+2.0)*(x+3.0)*(x+4.0));
#endif
return pi;
}
int main(const int argc, const char* const * const argv){
if(argc > 1)
printf("%.17g", calc_pi(atoi(argv[1])));
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment