Is there a reason why I am getting the same input over and over even though I am using np.random.choice()?

Viewed 128

I am given that someone playing Dungeons and Dragons (D&D) rolls a fair die with values 1-20 (one value per side) and that depending on the character I guess there is a modifier for each action that the character can make. In this case the modifier is 11 for opening a door. If the dice roll + modifier is greater than 15, the action is successful and the character opens the door if not, the action fails. This part of the question wants us to make an array of seven dice rolls and the score for that character with the modifier of 11.

This is what I have tried so far

import numpy as np
from datascience import *

modifier = 11
possible_rolls = np.arange(20)
roll_result = np.random.choice(possible_rolls)
modified_result = roll_result + modifier
num_observations = 7

def simulate_observations():
    """Produces an array of 7 simulated modified die rolls"""
    possible_rolls = np.arange(20)
    roll_result = np.random.choice(possible_rolls)
    modified_result = roll_result + modifier
    array = make_array()
    for i in np.arange(num_observations):
        array = np.append(array, modified_result)
    return array

observation_array = simulate_observations()
print(observation_array)

I'm expecting to get a various range of outputs based on a random roll of the dice and then adding that value to the modifier, then finally placing that final value in to the array named array but all I am getting is an array that looks like [20.,20.,20.,20.,20.,20.,20.]. Any ideas as to where I may be off? I'm 90% sure my issue is in my for loop as I have not quite grasped what exactly I am doing in them but I can't seem to pin down exactly what the problem is.

1 Answers

It is because you call np.random.choiceonly once, instead of once in each iteration in the for loop

import numpy as np
from datascience import *

modifier = 11
possible_rolls = np.arange(20)
roll_result = np.random.choice(possible_rolls)
modified_result = roll_result + modifier
num_observations = 7

def simulate_observations():
    """Produces an array of 7 simulated modified die rolls"""
    possible_rolls = np.arange(20)

    array = make_array()
    for i in np.arange(num_observations):
       # moved roll_result inside the loop
       roll_result = np.random.choice(possible_rolls)
       modified_result = roll_result + modifier
       array = np.append(array, modified_result)
    return array

observation_array = simulate_observations()
print(observation_array)
# [20. 11. 24. 11. 15. 16. 26.]

But you can also avoid the for loop and do directly

def simulate_observations():
    """Produces an array of 7 simulated modified die rolls"""
    possible_rolls = np.arange(modifier,20+modifier)
    return np.random.choice(possible_rolls,size=num_observations).tolist()
Related