Stat_prob_001
Stat_prob_001

Reputation: 181

while loop is not reading the variable

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.)

Upvotes: 0

Views: 91

Answers (4)

whackamadoodle3000
whackamadoodle3000

Reputation: 6748

Try this:

import numpy as np
def RVs():
   #s = 0
    s = 1
    f = 0
    while s!=0 or f==0: #will always run it the first time
        z = np.random.random()
        if z<=0.5:
            x = -1
        else:
            x = 1
        s = s + x
        f = f + 1
    return(f)
RVs()

Upvotes: 1

pashute
pashute

Reputation: 4053

Python does not have a do.... while() as in other languages. So just use a "first-time" operator.

import numpy as np
def RVs():
    s = 0
    t = 1 # first time in loop
    f = 0
    while s!=0 or t==1:
        t = 0 # not first time anymore
        z = np.random.random()
        if z<=0.5:
            x = -1
        else:
            x = 1
        s = s + x
        f = f + 1
return(f)
RVs()

Upvotes: 1

burgerhex
burgerhex

Reputation: 1048

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.

Upvotes: 3

AAvery
AAvery

Reputation: 128

From what I can understand you are trying to emulate a do while loop, where the loop will run at least one time(and you want the starting value of s to be 0)

If this is the case you can run the loop infinitely and break from the loop if your condition is true. For example:

while True:
    #code here
    if (s != 0):
        break

this will run your loop no matter what at least once, and will run the loop again at the end until your condition passes

Upvotes: 2

Related Questions