Skip to content

Instantly share code, notes, and snippets.

@cmaureir
Created August 9, 2012 14:06
Show Gist options
  • Save cmaureir/3304488 to your computer and use it in GitHub Desktop.
Save cmaureir/3304488 to your computer and use it in GitHub Desktop.
Pi-leibniz
#include <stdio.h>
#include <iostream>
#define N 10000
__global__ void pi_elem(float *values)
{
int i = threadIdx.x + blockIdx.x * blockDim.x;
if (i < N){
values[i] = pow((float)-1,(float)i);
values[i] /= (float)(2*i+1);
}
}
int main(int argc, char *argv[]) {
float pi = 0;
int i;
float *d_values, *h_values;
cudaMalloc((void**)&d_values,N*sizeof(float));
h_values = (float*)malloc(N*sizeof(float));
pi_elem <<< std::ceil(N/(float)32), 32 >>>(d_values);
cudaMemcpy(h_values,d_values,N*sizeof(float), cudaMemcpyDeviceToHost);
for (i = 0; i < N; i++) {
pi += h_values[i];
printf("%d %f\n",i, h_values[i]);
}
printf("%f\n", 4*pi);
return 0;
}
@rbonvall
Copy link

rbonvall commented Aug 9, 2012

Usar pow para calcular el signo es matar una mosca con un tanque. Los hípsters lo hacemos así:

values[i] = (i & 1) ? -1 : 1;
values[i] /= (float) (2 * i + 1);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment