python - Python 中的蒙特卡罗方法

标签 python montecarlo

我一直在尝试使用 Python 创建一个脚本,该脚本可以让我生成大量点以用于蒙特卡罗方法来计算 Pi 的估计值。到目前为止我的脚本是这样的:

import math
import random
random.seed()

n = 10000

for i in range(n):
    x = random.random()
    y = random.random()
    z = (x,y)

    if x**2+y**2 <= 1:
        print z
    else:
        del z

到目前为止,我能够生成我需要的所有点,但我想得到的是运行脚本时生成的点数,以供以后计算使用。我不是在寻找非常精确的结果,只是一个足够好的估计。任何建议将不胜感激。

最佳答案

如果您正在进行任何类型的繁重数值计算,请考虑学习 numpy。您的问题本质上是一个带有 numpy 设置的单线性问题:

import numpy as np

N   = 10000
pts = np.random.random((N,2))

# Select the points according to your condition
idx = (pts**2).sum(axis=1)  < 1.0
print pts[idx], idx.sum()

给予:

[[ 0.61255615  0.44319463]
 [ 0.48214768  0.69960483]
 [ 0.04735956  0.18509277]
 ..., 
 [ 0.37543094  0.2858077 ]
 [ 0.43304577  0.45903071]
 [ 0.30838206  0.45977162]], 7854

最后一个数字是计数事件的个数,即半径小于1的点的个数。

关于python - Python 中的蒙特卡罗方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13461567/

相关文章:

python - Numpy 的运行速度是 MATLAB 的一半

Python 函数 : Error with overtime while creating a wage function

python - Numpy:从较小的矩阵创建矩阵

random - 可以将Fortran 90的随机数生成器用于Monte Carlo集成吗?

python - 将 𝝅 计算为随机总和(蒙特卡罗)

python - 蒙特卡罗模拟 : Underlying distribution parameter changes during simulation run based on conditions

python - 如何在两个方向(向前,向后)获取每个元素的值的滑动窗口?

python - LinearRegression() 和 Ridge(alpha=0) 的区别

python - Tensorflow 可以计算积分近似的梯度吗?