CUDA:实现使用蒙特卡罗方法模拟π
下面是一个使用蒙特卡罗方法模拟π的示例代码:
#include <iostream>
#include <random>
#include <chrono>
__global__ void calculatePi(int *count, unsigned int seed) {
int tid = blockIdx.x * blockDim.x + threadIdx.x;
// Use XORShift32 algorithm for random number generation
unsigned int x = seed + tid;
x ^= (x << 13);
x ^= (x >> 17);
x ^= (x << 5);
// Transform the random number to a point in the unit square
float xPos = (float)(x & 0xFFFF) / 65535.0f;
float yPos = (float)((x >> 16) & 0xFFFF) / 65535.0f;
// Check if the point is inside the unit circle
if (xPos * xPos + yPos * yPos <= 1.0f) {
atomicAdd(count, 1);
}
}
int main() {
const int numPoints = 1000000;
co