简体   繁体   English

Python,for循环中的随机向量与随机数

[英]Python, Random vector vs Random number in an for loop

I am trying to solve some stochastic differential equations , with Gaussian noise . 我正在尝试用高斯噪声求解一些随机微分方程 I wonder if is better to use a Noise Vector : 我想知道使用噪声向量是否更好:

eta = np.random.normal(size=N)*sqrtdt
q = []
p = []
q.append(1.0)
p.append(1.0)
for i in range(N):
    q.append(f(q[i],p[i],eta[i])
    p.append(g(q[i],p[i],eta[i])

with f and g well behaved functions, or if I should create the random number in each iteration: 具有fg行为良好的函数,或者是否应该在每次迭代中创建随机数

q = []
p = []
q.append(1.0)
p.append(1.0)
for i in range(N):
    eta = np.random.normal()*sqrtdt
    q.append(f(q[i],p[i],eta)
    p.append(g(q[i],p[i],eta)

This code should be put into another for loop and run for several values of N , which varies from 10^4 to 10^9. 该代码应放入另一个for循环中,并运行多个N值,其范围从10 ^ 4到10 ^ 9。 I am also open to another way to write this, I know for loops are not the closest to Python mindset . 我也乐于接受另一种编写此方法的方法,我知道for循环并不是最接近Python心态的

There is no clear-cut reply to your problem in general and assuming that "ok" performance is enough. 通常,没有任何明确回答可以解决您的问题,并且假定“正常”性能就足够了。 There are actually three such strategies that I would consider here. 我实际上将在这里考虑三种策略。

  1. Generate all random values at the start. 在开始时生成所有随机值。 Pro: reduces call overhead during loop. 优点:减少循环期间的通话开销。 Con: Requires a lot of memory. 缺点:需要大量内存。
  2. Use an outer and an inner loop, where you generate the random values for the number of iterations of the inner loop only. 使用外部循环和内部循环,您可以在其中为内部循环的迭代次数生成随机值。
  3. Do all the work in the inner loop. 在内部循环中完成所有工作。 Pro: needs less memory. 优点:需要更少的内存。 Con: Maximum call overhead. 缺点:最大通话开销。

An interesting advantage of approach "2" is that you can accelerate the inner-loop with Cython (for instance) without changing the random number generator. 方法“ 2”的一个有趣的优点是,您可以使用Cython加速内部循环(例如),而无需更改随机数生成器。

You can store the current values of q and p to avoid fetching them from the list. 您可以存储qp的当前值,以避免从列表中获取它们。 You would append via q.append(q_loop) and p.append(p_loop) . 您可以通过q.append(q_loop)p.append(p_loop)追加。

Anyway, if performance is a concern you should benchmark the difference strategies and consider, in a second time, the use of "acceleration" (ie Cython, Numba, etc). 无论如何,如果要考虑性能,则应该对差异策略进行基准测试,并在第二次考虑使用“加速”(即Cython,Numba等)。 Time resolution of stochastic equations do not vectorize well, so NumPy strategies could not apply to you. 随机方程的时间分辨率不能很好地向量化,因此NumPy策略不适用于您。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM