| 1 | --- |
| 2 | tags: technical, python, properties, intro |
| 3 | date: 2016-07-04 00:00 |
| 4 | title: Calculating the mean of a list of numbers |
| 5 | author: drmaciver |
| 6 | --- |
| 7 | |
| 8 | Consider the following problem: |
| 9 | |
| 10 | You have a list of floating point numbers. No nasty tricks - these |
| 11 | aren't NaN or Infinity, just normal "simple" floating point numbers. |
| 12 | |
| 13 | Now: Calculate the mean (average). Can you do it? |
| 14 | |
| 15 | It turns out this is a hard problem. It's hard to get it even *close* to |
| 16 | right. Lets see why. |
| 17 | |
| 18 | <!--more--> |
| 19 | |
| 20 | Consider the following test case using Hypothesis: |
| 21 | |
| 22 | ```python |
| 23 | from hypothesis import given |
| 24 | from hypothesis.strategies import floats, lists |
| 25 | |
| 26 | |
| 27 | @given(lists(floats(allow_nan=False, allow_infinity=False), min_size=1)) |
| 28 | def test_mean_is_within_reasonable_bounds(ls): |
| 29 | assert min(ls) <= mean(ls) <= max(ls) |
| 30 | ``` |
| 31 | |
| 32 | This isn't testing much about correctness, only that the value of the |
| 33 | mean is within reasonable bounds for the list: There are a lot of |
| 34 | functions that would satisfy this without being the mean. min and max |
| 35 | both satisfy this, as does the median, etc. |
| 36 | |
| 37 | However, almost nobody's implementation of the mean satisfies this. |
| 38 | |
| 39 | To see why, lets write our own mean: |
| 40 | |
| 41 | ```python |
| 42 | def mean(ls): |
| 43 | return sum(ls) / len(ls) |
| 44 | ``` |
| 45 | |
| 46 | This seems reasonable enough - it's just the definition of the mean - |
| 47 | but it's wrong: |
| 48 | |
| 49 | ``` |
| 50 | assert inf <= 8.98846567431158e+307 |
| 51 | + where inf = mean([8.988465674311579e+307, 8.98846567431158e+307]) |
| 52 | + and 8.98846567431158e+307 = max([8.988465674311579e+307, 8.98846567431158e+307]) |
| 53 | |
| 54 | Falsifying example: test_mean_is_within_reasonable_bounds( |
| 55 | ls=[8.988465674311579e+307, 8.98846567431158e+307] |
| 56 | ) |
| 57 | ``` |
| 58 | |
| 59 | The problem is that finite floating point numbers may be large enough |
| 60 | that their sum overflows to infinity. When you then divide infinity by a |
| 61 | finite number you still get infinity, which is out of the range. |
| 62 | |
| 63 | So to prevent that overflow, lets try to bound the size of our numbers |
| 64 | by the length *first*: |
| 65 | |
| 66 | ```python |
| 67 | def mean(ls): |
| 68 | return sum(l / len(ls) for l in ls) |
| 69 | ``` |
| 70 | |
| 71 | ``` |
| 72 | assert min(ls) <= mean(ls) <= max(ls) |
| 73 | assert 1.390671161567e-309 <= 1.390671161566996e-309 |
| 74 | where 1.390671161567e-309 = min([1.390671161567e-309, 1.390671161567e-309, 1.390671161567e-309]) |
| 75 | and 1.390671161566996e-309 = mean([1.390671161567e-309, 1.390671161567e-309, 1.390671161567e-309]) |
| 76 | |
| 77 | Falsifying example: test_mean_is_within_reasonable_bounds( |
| 78 | ls=[1.390671161567e-309, 1.390671161567e-309, 1.390671161567e-309] |
| 79 | ) |
| 80 | ``` |
| 81 | |
| 82 | In this case the problem you run into is not overflow, but the lack of |
| 83 | precision of floating point numbers: Floating point numbers are only |
| 84 | exact up to powers of two times an integer, so dividing by three will |
| 85 | cause rounding errors. In this case we have the problem that (x / 3) * 3 |
| 86 | may not be equal to x in general. |
| 87 | |
| 88 | So now we've got a sense of why this might be hard. Lets see how |
| 89 | existing implementations do at satisfying this test. |
| 90 | |
| 91 | First let's try numpy: |
| 92 | |
| 93 | ```python |
| 94 | import numpy as np |
| 95 | |
| 96 | |
| 97 | def mean(ls): |
| 98 | return np.array(ls).mean() |
| 99 | ``` |
| 100 | |
| 101 | This runs into the problem we had in our first implementation: |
| 102 | |
| 103 | ``` |
| 104 | assert min(ls) <= mean(ls) <= max(ls) |
| 105 | assert inf <= 8.98846567431158e+307 |
| 106 | |
| 107 | where inf = mean([8.988465674311579e+307, 8.98846567431158e+307]) |
| 108 | and 8.98846567431158e+307 = max([8.988465674311579e+307, 8.98846567431158e+307]) |
| 109 | |
| 110 | Falsifying example: test_mean_is_within_reasonable_bounds( |
| 111 | ls=[8.988465674311579e+307, 8.98846567431158e+307] |
| 112 | ) |
| 113 | ``` |
| 114 | |
| 115 | There's also the new statistics module from Python 3.4. Unfortunately, |
| 116 | this is broken too |
| 117 | ([this is fixed in 3.5.2](https://bugs.python.org/issue25177)): |
| 118 | |
| 119 | ``` |
| 120 | OverflowError: integer division result too large for a float |
| 121 | |
| 122 | Falsifying example: test_mean_is_within_reasonable_bounds( |
| 123 | ls=[8.988465674311579e+307, 8.98846567431158e+307] |
| 124 | ) |
| 125 | ``` |
| 126 | |
| 127 | In the case where we previously overflowed to infinity this instead |
| 128 | raises an error. The reason for this is that internally the statistics |
| 129 | module is converting everything to the Fraction type, which is an |
| 130 | arbitrary precision rational type. Because of the details of where and |
| 131 | when they were converting back to floats, this produced a rational that |
| 132 | couldn't be readily converted back to a float. |
| 133 | |
| 134 | It's relatively easy to write an implementation which passes this test |
| 135 | by simply cheating and not actually calculating the mean: |
| 136 | |
| 137 | ```python |
| 138 | def clamp(lo, v, hi): |
| 139 | return min(hi, max(lo, v)) |
| 140 | |
| 141 | |
| 142 | def mean(ls): |
| 143 | return clamp(min(ls), sum(ls) / len(ls), max(ls)) |
| 144 | ``` |
| 145 | |
| 146 | i.e. just restricting the value to lie in the desired range. |
| 147 | |
| 148 | However getting an actually correct implementation of the mean (which |
| 149 | *would* pass this test) is quite hard: |
| 150 | |
| 151 | To see just how hard, here's a [30 page |
| 152 | paper on calculating the mean of two numbers](https://hal.archives-ouvertes.fr/file/index/docid/576641/filename/computing-midpoint.pdf). |
| 153 | |
| 154 | I wouldn't feel obliged to read that paper if I were you. I *have* read |
| 155 | it and I don't remember many of the details. |
| 156 | |
| 157 | This test is a nice instance of a general one: Once you've got the |
| 158 | [this code doesn't crash](../getting-started-with-hypothesis/), |
| 159 | tests working, you can start to layer on additional constraints on the |
| 160 | result value. As this example shows, even when the constraints you |
| 161 | impose are *very* lax it can often catch interesting bugs. |
| 162 | |
| 163 | It also demonstrates a problem: Floating point mathematics is *very* |
| 164 | hard, and this makes it somewhat unsuitable for testing with Hypothesis. |
| 165 | |
| 166 | This isn't because Hypothesis is *bad* at testing floating point code, |
| 167 | it's because it's good at showing you how hard programming actually is, |
| 168 | and floating point code is much harder than people like to admit. |
| 169 | |
| 170 | As a result, you probably don't care about the bugs it will find: |
| 171 | Generally speaking most peoples' attitude to floating point errors is |
| 172 | "Eh, those are weird numbers, we don't really care about that. It's |
| 173 | probably good enough". Very few people are actually prepared to do the |
| 174 | required work of a numerical sensitivity analysis that is needed if you |
| 175 | want your floating point code to be correct. |
| 176 | |
| 177 | I used to use this example a lot for demonstrating Hypothesis to people, |
| 178 | but because of these problems I tend not to any more: Telling people |
| 179 | about bugs they're not going to want to fix will get you neither bug |
| 180 | fixes nor friends. |
| 181 | |
| 182 | But it's worth knowing that this is a problem: Programming *is* really |
| 183 | hard, and ignoring the problems won't make it less hard. You can ignore |
| 184 | the correctness issues until they actually bite you, but it's best not |
| 185 | to be surprised when they do. |
| 186 | |
| 187 | And it's also worth remembering the general technique here, because this |
| 188 | isn't just useful for floating point numbers: Most code can benefit from |
| 189 | this, and most of the time the bugs it tells you won't be nearly this |
| 190 | unpleasant. |