如何根据一定的概率得到一个值
我有一些函数可以生成双精度、浮点、短、长随机值。我有另一个函数,我向其传递数据类型并且应该返回随机值。现在我需要在该函数中根据传递的数据类型选择返回值。例如,如果我传递float,我需要:
返回是float的概率是70%,返回是double、short或long的概率各是10%。我可以调用另一个函数来生成相应的随机值,但如何适应最终返回的概率权重?我的代码是C++的。
一些指示值得赞赏。
谢谢。
I have some functions which generate double, float, short, long random values. I have another function to which I pass the datatype and which should return a random value. Now I need to choose in that function the return value based on the passed datatype. For example, if I pass float, I need:
the probability that the return is a float is 70%, the probability that the return is a double, short or long is 10% each. I can make calls to the other function for generating the corresponding random values, but how do I fit in the probabilistic weights for the final return? My code is in C++.
Some pointers are appreciated.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
C++ 随机数具有均匀分布。如果您需要另一个随机变量。 org/wiki/Probability_distribution" rel="nofollow noreferrer">分布 您需要将其数学公式建立在均匀分布的基础上。
如果您没有随机变量的数学公式,您可以执行以下操作:
C++ random numbers have uniform distribution. If you need random variables of another distribution you need to base its mathematical formula on uniform distribution.
If you don't have a mathematical formula for your random variable you can do something like this:
这可以作为未来参考的替代方案
获得精确值的概率,例如 99.999% 或 0.0001%
要获得概率(实际百分比),请执行以下操作:
我使用此方法创建了非常大的渗透网格,它对于精确值来说就像一个魅力。
This can serve as an alternative for future references which can
get the probability of precise values such as 99.999% or 0.0001%
To get probability(real percentage) do as such:
I have used this method to create very large percolated grids and it works like a charm for precision values.
我不知道我是否正确理解你想要做什么,但如果你只是想确保概率为 70-10-10-10,请执行以下操作:
r
(1,2,3,4,5,6,7,8,9,10)r <= 7
: floatr == 8
: Shortr == 9
: doubler == 10
: long我认为您认识并可以使模式适应任意概率值。
I do not know if I understand correctly what you want to do, but if you just want to assure that the probabilities are 70-10-10-10, do the following:
r
in (1,2,3,4,5,6,7,8,9,10)r <= 7
: floatr == 8
: shortr == 9
: doubler == 10
: longI think you recognize and can adapt the pattern to arbitrary probability values.
mmonem 有一个很好的概率开关,但返回不同的类型也不是微不足道的。您需要一个可以充分(出于您的目的)对任何值进行编码的单一类型 - 查看 boost::any、boost::variant、union,或转换为最有能力的类型(可能是 double)或字符串表示形式。
mmonem has a nice probabilistic switch, but returning different types isn't trivial either. You need a single type that may adequately (for your purposes) encode any of the values - check out boost::any, boost::variant, union, or convert to the most capable type (probably double), or a string representation.