Shared Code
main.cu
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
#include <stdio.h> #include <cuda_runtime.h> __host__ __device__ float f(float x) { return x*x + 1.0f; } __global__ void Dev_trap( const float a, const float b, const float h, const int n, float* trap_p) { int my_i = blockDim.x * blockIdx.x + threadIdx.x; if (0 < my_i && my_i < n) { float my_x = a + my_i * h; float my_trap = f(my_x); atomicAdd(trap_p, my_trap); } } void Trap_wrapper( const float a, const float b, const int n, float* trap_p, const int blk_ct, const int th_per_blk) { float h = (b-a)/n; *trap_p = 0.5f * (f(a) + f(b)); Dev_trap<<<blk_ct, th_per_blk>>>( a, b, h, n, trap_p); cudaDeviceSynchronize(); *trap_p = h * (*trap_p); } int main() { float a = 0.0f, b = 3.0f; int n = 1000; int th_per_blk = 256; int blk_ct = (n + th_per_blk - 1) / th_per_blk; float* trap_p; cudaMallocManaged(&trap_p, sizeof(float)); Trap_wrapper(a, b, n, trap_p, blk_ct, th_per_blk); printf("With n = %d trapezoids, our estimate\n", n); printf("of the integral from %f to %f = %f\n", a, b, *trap_p); cudaFree(trap_p); return 0; }
Comments (0)
to post comments and vote
No comments yet. Be the first to share your thoughts!