在C ++中生成具有固定总和的随机值 [英] Generate random values with fixed sum in C++

查看:134
本文介绍了在C ++中生成具有固定总和的随机值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在网上看到了很多关于这个问题的答案,但是,你能相信我吗?我仍然没有解决这个问题.我有一个值数组.该数组的大小为"n".我也有定义的值"sum".我想要的是生成"n"个随机值,以使其总和等于"sum",最好均匀分布,否则(例如)具有第一个随机数等于"sum",其余等于零不太好我需要两种算法来完成此任务.一个带正整数,另一个带正浮点数.提前非常感谢!

I saw tons of answers to this question on the web but, can you believe me? I still don't get the solution of this problem. I have an array of values. The size of this array is "n". I have also the defined value "sum". What I want is to generate "n" random values in such a way that their sum is equals to "sum", preferably uniformly distributed, otherwise (for example) having the first random number equals to "sum" and the rest equals to zero is not that nice. I need two algorithms which accomplish this task. One with positive Integers and one with positive Floats. Thanks a lot in advance!

推荐答案

首先生成n个随机变量.然后总结一下:randomSum.计算系数总和/随机总和.然后将所有随机变量乘以该系数.

First generate n random variables. Then sum them up: randomSum. Calculate coefficient sum/randomSum. Then multiply all random variables with that coefficient.

整数可能会带来问题...四舍五入(可能)

Integers would pose a problem... Rounding too (probably)

这篇关于在C ++中生成具有固定总和的随机值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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