java按比例随机,java的随机百分比

更新时间:2023-06-23 10:31:59 阅读: 评论:0

java按⽐例随机,java的随机百分⽐
I need to generate n percentages (integers between 0 and 100) such that the sum of all n numbers adds up to 100.
饸饹面图片If I just do nextInt() n times, each time ensuring that the parameter is 100 minus the previously accumulated sum, then my percentages are biad (i.e. the first generated number will usually be largest etc.). How do I do this in an unbiad way?
解决⽅案
人大职责A couple of answers suggest picking random percents and taking the differences between them. As Nikita Ryback points out, this will not give the uniform distribution over all possibilities; in particular, zeroes will be less frequent than expected.
制的成语To fix this, think of starting with 100 'percents' and inrting dividers. I will show an example with 10:
% % % % % % % % % %
色四月There are eleven places we could inrt a divider: between any two percents or at the beginning or end. So inrt one:
% % % % / % % % % % %
This reprents choosing four and six. Now inrt another divider. This time, there are twelve places, becau the divider already inrted creates and extra one. In particular, there are two ways to get英语唯美短句
审计建议% % % % / / % % % % % %非布司他说明书
either inrting before or after the previous divider. You can continue the process until you have as many dividers as you need (one fewer than the number of percents.)
% % / % / % / / % % % / % % % /
This corresponds to 2,1,1,0,3,3,0.
We can prove that this gives the uniform distribution. The number of compositions of 100 into k parts is the binomial coefficient 100+k-1 choo k-1. That is
(100+k-1)(100+k-2)...101 / (k-1)(k-2)*...*2*1
Thus the probability of choosing any particular composition is the reciprocal of this. As we inrt divid
ers one at a time, first we choo from 101 positions, then 102, 103, etc until we get to 100+k-1. So the probability of any particular quence of inrtions is 1 / (100+k-1)*...*101. How many inrtion quences give ri to the same composition? The final composition contains k-1 dividers. They could have been inrted in any order, so there are (k-1)! quences that give ri to a given composition. So the probability of any particular composition is exactly what it should be.
In actual code, you probably wouldn't reprent your steps like this. You should be able to just hold on to numbers, rather than quences of percents and dividers. I haven't thought about the complexity of this algorithm.七年级英语

本文发布于:2023-06-23 10:31:59,感谢您对本站的认可!

本文链接:https://www.wtabcd.cn/fanwen/fan/89/1051141.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

标签:建议   说明书   审计   布司
相关文章
留言与评论(共有 0 条评论)
   
验证码:
推荐文章
排行榜
Copyright ©2019-2022 Comsenz Inc.Powered by © 专利检索| 网站地图