I want to generate random numbers from two different ranges [0, 0.3) and [0.7, 1) in python.
numpy.random.uniform
has the option of generating only from one particular interval.
I want to generate random numbers from two different ranges [0, 0.3) and [0.7, 1) in python.
numpy.random.uniform
has the option of generating only from one particular interval.
I assume you want to choose an interval with probability weighted by its size, then sample uniformly from the chosen interval. In that case, the following Python code will do this:
import random
# Define the intervals. They should be disjoint.
intervals=[[0, 0.05], [0.7, 1]]
# Choose one number uniformly inside the set
random.uniform(*random.choices(intervals,
weights=[r[1]-r[0] for r in intervals])[0])
import numpy
# Generate a NumPy array of given size
size=1000
numpy.asarray([ \
random.uniform(*random.choices(intervals,
weights=[r[1]-r[0] for r in intervals])[0]) \
for i in range(1000)])
Note that the intervals you give, [[0, 0.3], [0.7, 1]]
, appear to be arbitrary; this solution works for any number of disjoint intervals, and it samples uniformly at random from the union of those intervals.
How about this one?
first_interval = np.array([0, 0.3])
second_interval = np.array([0.7, 1])
total_length = np.ptp(first_interval)+np.ptp(second_interval)
n = 100
numbers = np.random.random(n)*total_length
numbers += first_interval.min()
numbers[numbers > first_interval.max()] += second_interval.min()-first_interval.max()
Refer to this thread hope it solves your query. But the answer is as follows :
def random_of_ranges(*ranges):
all_ranges = sum(ranges, [])
return random.choice(all_ranges)
print(random_of_ranges(range(65, 90), range(97, 122)))
You can just concatenate random numbers from those two intervals.
import numpy as np
rng = np.random.default_rng(12345)
a = rng.uniform(0, 0.3,1000)
b = rng.uniform(0.7, 1,1000)
my_rnd = np.concatenate([a, b])
These look fairly uniform across the two intervals.