简体   繁体   中英

Function generates different random number each time

By using Python, How can I make x,y, and z values different by having a different random number q between (0,1) each time when I use q through the whole code? #####################################################

import random



def get_rand_number(min_value, max_value):
    """
    This functions gets a random number from a uniform distribution between
    the two input values [min_value, max_value] inclusively
    Args:
    - min_value (float)
    - max_value (float)
    Return:
    - Random number between this range (float)
    """
    range = max_value - min_value
    choice = random.uniform(0,1)
    return min_value + range*choice

q = get_rand_number(0,1)


x = 2 * q
y = 2 * q
z = 2 * q

print (x)
print (y)
print(z)

########################################

output: 0.0008081435950477722, 0.0008081435950477722, 0.0008081435950477722

I believe what you mean is that q must have different values every time it is multiplied by 2 in the x , y , z values.

This is what I think the solution is.

import random

// The get_rand_number was unnecessary so I'm removing that.

x = 2 * random.uniform(0,1)
y = 2 * random.uniform(0,1)
z = 2 * random.uniform(0,1)

print(x)
print(y)
print(z)

You get one random value and save it in the q variable and then use the same value in all three dimensions ( x, y, z ):

q = get_rand_number(0,1)

x = 2 * q
y = 2 * q
z = 2 * q

If you want to have three different random number then call the random number generation for the three dimensions:

x = 2 * get_rand_number(0,1)
y = 2 * get_rand_number(0,1)
z = 2 * get_rand_number(0,1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM