Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get one random float number from two ranges (python)

I need to choose a random float number in two ranges in python:

0. < n < 0.2  or  0.8 < n < 1.

Right now I only have one range:

random.uniform(0, 0.2)

The full line (I'm mapping warm color hsv values):

couleur = hsv2rgb(random.uniform(0, 0.2), 1, 1))

If someone could help... !

like image 354
SelmaB Avatar asked Mar 10 '23 02:03

SelmaB


1 Answers

You can do a weighted selection between the intervals:

from numpy import random

def uniform_two(a1, a2, b1, b2):
    # Calc weight for each range
    delta_a = a2 - a1
    delta_b = b2 - b1
    if random.rand() < delta_a / (delta_a + delta_b):
        return random.uniform(a1, a2)
    else:
        return random.uniform(b1, b2)

print uniform_two(0, 0.2, 0.8, 1)
like image 50
J. P. Petersen Avatar answered Apr 25 '23 13:04

J. P. Petersen