[英]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: 具有f和g行为良好的函数,或者是否应该在每次迭代中创建随机数 :
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.
我实际上将在这里考虑三种策略。
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. 您可以存储
q
和p
的当前值,以避免从列表中获取它们。 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.