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()
The code is running smoothly if I put s=1
but since the while loop is for s!=0
, if I start with s=0
the loop is not even running. So, what should I do in this case when I have to run the code for s=0
. (Or more precisely, I need to while loop to read s=0
is the second time.)
The other solution is great. Here's a different approach:
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()
Note: return(f)
needs to be indented in your original code to be inside the RVs
function.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments