while 循环未读取变量

Stat_prob_001
import numpy as np
def RVs():
   #s = 0
    s = 1
    f = 0
    while s!=0:
        z = np.random.random()
        if z<=0.5:
            x = -1
        else:
            x = 1
        s = s + x
        f = f + 1
    return(f)
RVs()

如果我把代码运行顺利,s=1但由于 while 循环是 for s!=0,如果我从s=0循环开始甚至没有运行。那么,在这种情况下,当我必须运行s=0. (或者更准确地说,我需要 while 循环读取s=0是第二次。)

艾维·沙伊

另一个解决方案很棒。这是一种不同的方法:

import numpy as np

def RVs():
    # s = 0
    s = 1
    f = 0

    while True: # will always run the first time...
        z = np.random.random()

        if z <= 0.5:
            x = -1
        else:
            x = 1

        s = s + x
        f = f + 1

        if s == 0: break # ... but stops when s becomes 0

    return(f)

RVs()

注意:return(f)需要在原始代码中缩进才能在RVs函数内。

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章