2 of 4 Fix punctiation

More Accurate Random in C

I have 3 IPs and every IP has a weight, I want to return the IP's according to its weights using the random function. For example if we have 3 IP's

  • X with weight 6
  • Y with weight 4
  • and Z with weight 2

I want to return X in 50% of cases and Y in 33% of cases and Z in 17% of cases, depending on random function in C.

I have tried this code :

double r = rand() / (double)RAND_MAX;
double denom = 3 + 3 + 3;
if (r < 3 / denom) {
// choose X
} else if (r < (3 + 3) / denom) {
// choose Y 
} else {
// choose Z
}

I repeat the function 1000 and I get: Choose x 495 times and Choose y 189 times and choose z 316 times. But what I want is to get X:333 y:333 Z:334 How can the weighted random be more accurate?