如何基于一定概率获得值

编程入门 行业动态 更新时间:2024-10-23 07:36:17
本文介绍了如何基于一定概率获得值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一些函数可以生成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 }

更多推荐

如何基于一定概率获得值

本文发布于:2023-11-30 02:51:56,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1648474.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:概率

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!