Walshy
Walshy

Reputation: 850

Total of percentages is not correct

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

Answers (3)

simmons2714
simmons2714

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

Andrew
Andrew

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

sidgate
sidgate

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

Related Questions