Reputation: 850
I am distributing tokens but they are not all distributed. I have multiple percentages and get the amount of tokens to give for that percentage but they do not equal up to the total.
Example:
int tokens = 50;
double[] percentages = new double[] {0.3725, 0.219, 0.115, 0.2935};
int total = 0;
for(double d : percentages){
int amount = (int) (tokens * d);
total += amount;
}
The total is 47 though. I have also tried to round it with Math.round
for(double d : percentages){
double rounded = Math.round(d * 100);
int amount = (int) (tokens * (rounded / 100));
total += amount;
}
The total is 49
I can never seem to get 50, it is always below or above. I want to distribute these tokens are evenly as possible. If you can help please do!!
Upvotes: 1
Views: 92
Reputation: 17
I'm not sure why this works but I changed the total code to
total += income/1.025;
I think it works because while the loop doesn't display the age for 68 it still runs through one last time. So you'd have to undo the rate for retirement.
Upvotes: 0
Reputation: 3061
What you should do is round down the percentages as you were originally (casting to int). Then look at how many tokens you have left over. These should be distributed to the cases that are furthest away from their true value.
In each case the error would be:
double error = (percentage * tokens) - (int)(percentage * tokens);
Sort your cases by error, and award the tokens to the cases with the largest error until you have given out all 50.
Upvotes: 1
Reputation: 15244
Use double
total
. Using int leads to loss of decimal information
double total = 0;
for(double d : percentages){
double amount = (tokens * d);
total += amount;
}
Upvotes: 2