【问题标题】:How to improve Brownian motion monte carlo simulation speed?如何提高布朗运动蒙特卡罗模拟速度?
【发布时间】:2019-08-07 00:43:55
【问题描述】:

我想让我的代码运行得更快,以便进行更多的迭代和运行。现在我的代码太慢了,但我不知道要改变什么来加快它。 我开始编写动力学蒙特卡罗模拟,然后将其编辑为布朗运动模拟。我当前的代码无法处理 10,000 次运行,每次运行 10,000 次迭代,这是必需的。

import numpy as np
import matplotlib.pyplot as plt
import time
%matplotlib inline

runs = int(input("Enter number of runs: "))
N = int(input("Enter number of iterations per simulation: "))

y = 0
R = 10*1  # R is the rate value
t0 = time.time()
for y in range(runs):  # Run the simulation 'runs' times
    T = np.array([0])
    dt = 0
    x = 0.5  # sets values 
    X = np.array([x])
    t = 0
    i = 0

    while t < N:  # N is the number of iterations per run
        i = i + 1  # i is number of iterations so far
        z = np.random.uniform(-1, 1, 1)  # sets z to be a random number between -1 to 1 size 1

        if z > (1/3):  # if conditions for z for alpha and gamma, beta 
            x = x + 1  # z[]=alpha state then + 1
        elif z < (-1/3):
            x = x-1  # z[]=gamma state then - 1
        elif z < (1/3) and z > (-1/3):
            x = x  # z=beta state then + 0

        X = np.append(X, x)  # adds new X value to original X array
        X[i] += X[i-1] * 0.01 * np.random.normal(0, 1, 1) * np.sqrt(dt)  # for Brownian motion with sigma as 0.01
        Z = np.random.uniform(0, 1)  # sets Z to be a random number between 0 and 1
        dt = 1/R * np.log(1/Z)  # formula for dt; R is the rate value
        t = t + dt  # ITERATED TIME
        T = np.append(T, t)
        plt.plot(T, X, lw='0.5', alpha=0.5)

t1 = time.time()
print("final %.10f seconds " % (t1-t0))

【问题讨论】:

  • 请编辑您的代码(主要是缩进)以确保我们正确解释它
  • 注意:如果您切换到描述性变量名称会有所帮助。无论如何,plt.plot 是否需要在内部循环中?好像还可以追。另外,T 看起来不需要是np.array,所以保留T = [] 并使用T.append(t)。另一件事是,看起来 NumPy 大部分时间都在单个元素上使用,这不是它的快速之处;你也可以使用标准库。
  • 努力矢量化你的代码。而不是例如单值模拟运行 10,000 次(您的 z 是一个数字),具有 10,000 次模拟的向量。
  • @Ry 在内部循环中将多个图绘制到同一个图上,因为当我们增加运行时,我需要显示图的平均值,平均值应该接近 0。跨度>
  • @pythonnewbie22:看起来你每次都在用一个新项目绘制相同的图。似乎它应该在外循环中,在内循环之后。

标签: python montecarlo stochastic event-simulation


【解决方案1】:

Here is an excellent example 的快速运行的布朗运动蒙特卡罗模拟,计算成本较低。

我过去和你做过同样的事情,并且每次迭代的每一步都在嵌套循环中进行。也许是上下文切换的成本,通过不同的库运行,或者只是内存不足,但是在每次迭代中运行代码的每一步肯定会带来更慢的性能和更高的内存使用。

在上面的例子中,作者首先创建数组,然后然后用一个for循环相应地迭代它们。所有的随机数同时生成并放入一个数组中。然后同时计算所有布朗运动回报。等等(想象一条装配线——在每一步都很好地利用资源并获得规模经济。)同样重要的是,请注意 plt 函数只运行一次(不在循环内)并且只有在所有迭代都完成之后完全的。

这种方法应该允许在更小的硬件上进行更多的迭代。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-10
    • 1970-01-01
    • 1970-01-01
    • 2017-02-18
    • 1970-01-01
    • 2012-11-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多