-2

I am having unexpected outputs with the following code:

import random

N = 30  # number of steps

n = random.random()  # generate a random number

x = 0
y = 0
z = 0
count = 0 
while count <= N:

if n < 1/3:
    x = x + 1           # move east
    n = random.random() # generate a new random number

if n >= 1/3 and n < 2/3:
    y = y + 1           # move north
    n = random.random() # generate a new random number

if n >= 2/3:
    z = z + 1           # move up
    n = random.random() # generate a new random number


print("(%d,%d,%d)" % (x,y,z))
count = count + 1

When I run the code, the problem is:

  • Code output displays 31 coordinates, 1 more than the number of steps (N) variable.
  • Each iteration for 1 step should take only 1 step but it sometimes take multiple steps.

When I tested the code, the problem is ensured. To test the code, I assigned N = 1, and saw the following output:

  • (-1,0,1) This should be the initial step, but it took multiple steps (both x-1 and z+1), how could this happen?

  • (-2,0,1) Number of step variable (N) = 1 but this is the second output, why was it displayed? Thanks for helping

Jenny Azaz
  • 11
  • 1
  • 1
  • 1
    Your line by line debugger will answer all this with aplomb. – Bathsheba Sep 20 '16 at 07:02
  • 4
    http://stackoverflow.com/questions/39587461/random-walks-weird-outcome-in-python-3 Your code seems very similar, is this perhaps some assignment left for a group of students? Just asking, since this just got posted a few minutes ago. – Teemu Risikko Sep 20 '16 at 07:09

2 Answers2

3
  1. N is 30, so count goes from 0 to 30. Since 30 <= 30 you will run the loop for count=0, 1, ..., 29 AND 30 which is 31 times

  2. When you take a step, you don't ensure that another step is NOT taken. If random happens, you could enter the second or third if after already being in a previous one in the same loop iteration

Moberg
  • 5,253
  • 4
  • 38
  • 54
-1

You are dividing two ints which will only result in another int. So basically your code is do the following:

if n < 0:
    x = x + 1           # move east
    n = random.random() # generate a new random number

if n >= 0 and n < 1:
    y = y + 1           # move north
    n = random.random() # generate a new random number

if n >= 1:
    z = z + 1           # move up
    n = random.random()

fix by changing each if line to include a floating point number

if n < 1.0/3
Ben Romano
  • 98
  • 1
  • 5
  • Dividing two integers is only an integer in Python 2. In Python 3, "true division" (using the `/` operator) between integers gives a `float`. The question isn't tagged with a Python version, but the `print` function calls make it look like Python 3 to me. – Blckknght Sep 20 '16 at 07:14