|
| 1 | +import java.lang.Math; |
| 2 | +import java.util.stream.DoubleStream; |
| 3 | + |
| 4 | +public class ApproximateCounting { |
| 5 | + |
| 6 | + /* |
| 7 | + * This function taks |
| 8 | + * - v: value in register |
| 9 | + * - a: a scaling value for the logarithm based on Morris's paper |
| 10 | + * It returns the approximate count |
| 11 | + */ |
| 12 | + static double n(double v, double a) { |
| 13 | + return a * (Math.pow(1 + 1 / a, v) - 1); |
| 14 | + } |
| 15 | + |
| 16 | + |
| 17 | + /* |
| 18 | + * This function takes |
| 19 | + * - v: value in register |
| 20 | + * - a: a scaling value for the logarithm based on Morris's paper |
| 21 | + * It returns the new value for v |
| 22 | + */ |
| 23 | + static double increment(double v, double a) { |
| 24 | + double delta = 1 / (n(v + 1, a) - n(v, a)); |
| 25 | + |
| 26 | + if (Math.random() <= delta) { |
| 27 | + return v + 1; |
| 28 | + } else { |
| 29 | + return v; |
| 30 | + } |
| 31 | + } |
| 32 | + |
| 33 | + |
| 34 | + |
| 35 | + /* |
| 36 | + * This function takes |
| 37 | + * - v: value in register |
| 38 | + * - a: a scaling value for the logarithm based on Morris's paper |
| 39 | + * It returns the new value for v |
| 40 | + */ |
| 41 | + static double approximateCount(int nItems, double a) { |
| 42 | + double v = 0; |
| 43 | + |
| 44 | + for (int i = 0; i < nItems; i++) { |
| 45 | + v = increment(v, a); |
| 46 | + } |
| 47 | + |
| 48 | + return n(v, a); |
| 49 | + } |
| 50 | + |
| 51 | + /* |
| 52 | + * This function takes |
| 53 | + * - nTrials: the number of counting trails |
| 54 | + * - nItems: the number of items to count |
| 55 | + * - a: a scaling value for the logarithm based on Morris's paper |
| 56 | + * - threshold: the maximum percent error allowed |
| 57 | + * It terminates the program on failure |
| 58 | + */ |
| 59 | + static void testApproximateCount(int nTrials, int nItems, double a, double threshold) { |
| 60 | + double avg = DoubleStream.generate(() -> approximateCount(nItems, a)) |
| 61 | + .limit(nTrials) |
| 62 | + .average() |
| 63 | + .getAsDouble(); |
| 64 | + |
| 65 | + if (Math.abs((avg - nItems) / nItems) < threshold) { |
| 66 | + System.out.println("passed"); |
| 67 | + } else { |
| 68 | + System.out.println("failed"); |
| 69 | + } |
| 70 | + } |
| 71 | + |
| 72 | + |
| 73 | + public static void main(String args[]) { |
| 74 | + System.out.println("[#]\nCounting Tests, 100 trials"); |
| 75 | + System.out.println("[#]\ntesting 1,000, a = 30, 10% error"); |
| 76 | + testApproximateCount(100, 1_000, 30, 0.1); |
| 77 | + |
| 78 | + System.out.println("[#]\ntesting 12,345, a = 10, 10% error"); |
| 79 | + testApproximateCount(100, 12_345, 10, 0.1); |
| 80 | + |
| 81 | + System.out.println("[#]\ntesting 222,222, a = 0.5, 20% error"); |
| 82 | + testApproximateCount(100, 222_222, 0.5, 0.2); |
| 83 | + } |
| 84 | + |
| 85 | +} |
0 commit comments