A formula can be implemented perfectly and still give the wrong answer
I spent a while this year writing a small zero-dependency library of health and fitness formulas — BMI, Mifflin-St Jeor, the US Navy body-fat equation, FFMI, Epley and Brzycki, Karvonen. Thirty-odd functions, no dependencies, ESM, one file. It should have been a boring job. It mostly was. But three things came out of it that I think generalise well beyond fitness maths, and one of them genuinely changed how I think about what "correct" means in a library. The boring part: these equations get reimplemented constantly, and quietly wrong Search for any of these formulas and you will find dozens of implementations. A lot of them are subtly broken, in ways that never throw and never look wrong: The wrong coefficient set. The Navy body-fat equation has separate male and female forms, and separate metric and imperial constants. Four combinations, and three of them are wrong for any given call. The imperial equation fed metric input. Nothing errors. You just get a number that is wrong by a believable margin, which is the worst kind of wrong. Rounding in the middle. More on this below, because it turned out to be the interesting one. None of these produce a NaN or a stack trace. They produce a plausible number. That is the entire problem: there is no failure signal, so the bug survives indefinitely. My response was unremarkable — every function names the paper it came from in a docblock, and nothing is rounded inside the library. You round for display, because only you know how many decimal places your UI has room for. The interesting part: rounding order is observable, so it has to be pinned Total daily energy expenditure is BMR times an activity multiplier. Trivial. Except: do you round the BMR before multiplying, or round only the final figure? It matters, and it is measurable: const args = { sex: 'female', kg: 70.5, cm: 167, age: 41 }; const raw = bmrMifflinStJeor(args); // 1382.75 Math.round(Math.round(raw) * 1.725); // 2386
This is a summary aggregated from Dev.to. Read the complete article on the original site:
Read full article at Dev.to