| 44 | */ |
| 45 | |
| 46 | static int64_t hypergeometric_sample(bitgen_t *bitgen_state, |
| 47 | int64_t good, int64_t bad, int64_t sample) |
| 48 | { |
| 49 | int64_t remaining_total, remaining_good, result, computed_sample; |
| 50 | int64_t total = good + bad; |
| 51 | |
| 52 | if (sample > total/2) { |
| 53 | computed_sample = total - sample; |
| 54 | } |
| 55 | else { |
| 56 | computed_sample = sample; |
| 57 | } |
| 58 | |
| 59 | remaining_total = total; |
| 60 | remaining_good = good; |
| 61 | |
| 62 | while ((computed_sample > 0) && (remaining_good > 0) && |
| 63 | (remaining_total > remaining_good)) { |
| 64 | // random_interval(bitgen_state, max) returns an integer in |
| 65 | // [0, max] *inclusive*, so we decrement remaining_total before |
| 66 | // passing it to random_interval(). |
| 67 | --remaining_total; |
| 68 | if ((int64_t) random_interval(bitgen_state, |
| 69 | remaining_total) < remaining_good) { |
| 70 | // Selected a "good" one, so decrement remaining_good. |
| 71 | --remaining_good; |
| 72 | } |
| 73 | --computed_sample; |
| 74 | } |
| 75 | |
| 76 | if (remaining_total == remaining_good) { |
| 77 | // Only "good" choices are left. |
| 78 | remaining_good -= computed_sample; |
| 79 | } |
| 80 | |
| 81 | if (sample > total/2) { |
| 82 | result = remaining_good; |
| 83 | } |
| 84 | else { |
| 85 | result = good - remaining_good; |
| 86 | } |
| 87 | |
| 88 | return result; |
| 89 | } |
| 90 | |
| 91 | |
| 92 | // D1 = 2*sqrt(2/e) |
no test coverage detected