我想在python中从两个不同的范围[0,0.3)和[0.7,1]生成随机数。
numpy.random.uniform
可以选择只从一个特定的时间间隔生成。
发布于 2021-08-10 06:45:02
这个怎么样?
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()
发布于 2021-08-10 06:45:29
我假设你想要选择一个按其大小加权概率的区间,然后从所选区间中均匀抽样。在这种情况下,以下Python代码将执行此操作:
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)])
请注意,您给出的间隔[[0, 0.3], [0.7, 1]]
似乎是任意的;此解决方案适用于任意数量的不相交间隔,并且它从这些间隔的并集中随机均匀地采样。
发布于 2021-08-10 06:42:08
请参考这个帖子,希望它能回答你的问题。但答案如下:
def random_of_ranges(*ranges):
all_ranges = sum(ranges, [])
return random.choice(all_ranges)
print(random_of_ranges(range(65, 90), range(97, 122)))
https://stackoverflow.com/questions/68722002
复制相似问题