So, basically, I have two ranges. "Narrow range" is any number from -0.5 to 0.3 (up to 5 decimal places), and the "Full range" is any number from -1 to 1. To select a random value, for each, I do the following:
narrowrange=np.random.uniform(-.5,.3)
fullrange=np.random.uniform(-1,1)
However, I would like to create a new range, which subtracts the narrowrange from the fullrange. In other words, I'd like to select random numbers from -1 to -0.5 and 0.3 to 1 (so excluding any numbers from the narrow range).
The only way I can think of doing this is by creating an if statement for the full range (if this generated # falls into the narrow range, then generate a # again). Anyone know how to do this without for loops/if statements?
CodePudding user response:
You can use np.random.choice
with a list of random.uniform
as parameter
np.random.choice([np.random.uniform(-1, -.5), np.random.uniform(.3, 1)])
If you would like to add weight as suggested in the comments you can use the p
parameter
total = -.5 1 1 - .3
p = [(-.5 1) / total, (1 - .3) / total]
np.random.choice([np.random.uniform(-1, -.5), np.random.uniform(.3, 1)], p=p)
CodePudding user response:
I can't think of how to do it without an if statement, but I can do it without the risk of multiple tries.
Your full range of values is 1.2 (-1 to -0.5 is a range of 0.5, and 0.3 to 1 is a range of 0.7, so that's 1.2 in total).
I would suggest picking a random number in the range 1.2, and then shifting that value into one of the two ranges based on where it lies:
unshifted = np.random.uniform(0, 1.2)
if unshifted <= 0.5:
shifted = unshifted - 1
else:
shifted = unshifted - 0.2