我对下面的算法有疑问。让我困惑的是为什么 x = random.random()*2 -1
和 y = random.random()*2 -1
而不是简单的 x = random.random()
和 y = random.random()
?完整代码如下:
import random
NUMBER_OF_TRIALS= 1000000
numberOfHits = 0
for i in range(NUMBER_OF_TRIALS):
x = random.random()*2 -1
y = random.random()*2 -1
if x * x + y * y <=1:
numberOfHits +=1
pi = 4* numberOfHits / NUMBER_OF_TRIALS
print("PI is", pi)
最佳答案
这个模拟中的圆以 (0, 0) 为中心,半径为 1,所以
x = random.random() * 2 - 1
y = random.random() * 2 - 1
将使每个范围为 -1 到 1。
关于python - 蒙特卡洛模拟使用圆估计 pi,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51773034/