生成范围内的随机数 [英] Generate a Random Number within a Range
问题描述
我以前已经做过,但是现在我又在挣扎着,我认为我不理解问题背后的数学原理.
I have done this before, but now I'm struggling with it again, and I think I am not understanding the math underlying the issue.
我想在1
任一侧的小范围内设置一个随机数.示例将是.98
,1.02
,.94
,1.1
等.我发现的所有示例都描述了在0
和100
之间获得随机数,但是如何使用它来获得我想要的范围?
I want to set a random number on within a small range on either side of 1
. Examples would be .98
, 1.02
, .94
, 1.1
, etc. All of the examples I find describe getting a random number between 0
and 100
, but how can I use that to get within the range I want?
尽管我使用的是Pure Data,但编程语言在这里并不重要.有人可以解释一下所涉及的数学吗?
The programming language doesn't really matter here, though I am using Pure Data. Could someone please explain the math involved?
推荐答案
制服
如果您希望在0.9到1.1之间(伪间隔)均匀分布(均匀分布),则可以使用以下方法:
Uniform
If you want a (psuedo-)uniform distribution (evenly spaced) between 0.9 and 1.1 then the following will work:
range = 0.2
return 1-range/2+rand(100)*range/100
相应地调整范围.
如果您想要正态分布(钟形曲线),则需要特殊的代码,该代码将特定于语言/库.您可以使用以下代码获得近似值:
If you wanted a normal distribution (bell curve) you would need special code, which would be language/library specific. You can get a close approximation with this code:
sd = 0.1
mean = 1
count = 10
sum = 0
for(int i=1; i<count; i++)
sum=sum+(rand(100)-50)
}
normal = sum / count
normal = normal*sd + mean
这篇关于生成范围内的随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!