Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
400 views
in Technique[技术] by (71.8m points)

ruby - How to deal with the sum of rounded percentage not being 100?

Suppose we have a list of items with an integer:

USA:       3 people
Australia: 2 people
Germany:   2 people

If we calculate the percentage of each value against the sum over the whole list, we get:

USA:       3/(3+2+2)*100 = 42.857...%
Australia: 2/(3+2+2)*100 = 28.571...%
Germany:   2/(3+2+2)*100 = 28.571...%

and if we round it, we get:

USA:       43%
Australia: 29%
Germany:   29%

The sum 43+29+29 = 101 is not 100, and it looks a little bit strange to the user of the software. How would you solve this problem?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can refer to the Largest Remainder Method used in election: Wikipedia: Largest Remainder Method

In your case, you have

USA:       42.857...
Australia: 28.571...
Germany:   28.571...

If you take the integer part, you get

USA:       42
Australia: 28
Germany:   28

which adds up to 98, and you want to take two more. Now, you look at the decimal parts, which are

USA:       0.857...
Australia: 0.571...
Germany:   0.571...

and take the largest ones until the total reaches 100. If you take USA, the total becomes 99, and you want to take one more. Here the problem arises. Since you are left with a tie of 0.571... between Australia and Germany, if you take both, the total will be 101. So you have two ways to choose from:

(a) If you strongly want the total to be 100, just take Australia, and take no more:

USA:       43
Australia: 29
Germany:   28

(b) If you rather want to respect the fact that Australia and Germany are in a tie, you stop at that point:

USA:       43
Australia: 28
Germany:   28

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...