如何基于一定概率获得值 [英] How to obtain a value based on a certain probability

查看:90
本文介绍了如何基于一定概率获得值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些函数可以生成double,float,short,long随机值.我有另一个函数,该函数将数据类型传递给该函数,并且应该返回一个随机值.现在,我需要在该函数中根据传递的数据类型选择返回值.例如,如果我通过float,则需要:

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:

返回为浮点型的概率为70%,返回为double,short或long的概率分别为10%.我可以调用另一个函数来生成相应的随机值,但是如何使概率权重适合最终的收益呢?我的代码是C ++.

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.

谢谢.

推荐答案

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:

int x = rand() % 10;
if (x < 7)
{
 // return float
}
else (if x == 7)
{
 // return double
}
else (if x == 8)
{
 // return short
}
else (if x == 9)
{
 // return long
}

这篇关于如何基于一定概率获得值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆