Most of the hard parts of a dosing calculator are not the arithmetic. They are the
units, and the fact that a user will happily type a number in whichever unit their supplies
happen to be labelled with.
Three things that cost me real debugging time:
1. Never store a mixed unit. I started with a dose column holding whatever the user typed
and a unit column beside it. Every query then had to branch. The fix was boring and correct:
normalise to one base unit (micrograms) at the edge, store an integer, and format back to the
display unit only in the view layer. Integers also sidestep the float problem below.
2. Floating point ruins reconstitution math. Reconstitution is a ratio: total substance
divided by solvent volume gives concentration, and dose divided by concentration gives the
volume to draw. Chain three float divisions and you get numbers like 0.30000000000000004
units, which looks broken even though it is off by 1e-17. I moved the whole chain to integer
micrograms and integer microlitres and rounded once, at the end, to the precision the syringe
markings actually allow. Rounding once at the boundary rather than at each step is the whole
trick.
3. Round to the instrument, not to the number. A syringe marked in 0.02 unit increments
cannot deliver 0.317. Displaying a value nobody can measure is worse than displaying a
slightly wrong one, because the user has to invent the rounding themselves. So the formatter
takes the increment as an argument and snaps to it.
None of this is novel, but the general lesson generalised well for me: any app where the user
supplies a physical quantity wants a single canonical unit, integer storage, one rounding step,
and a formatter that knows what the real world can actually resolve.
I wrote most of this up while building a peptide tracker and calculator
as a side project. The reconstitution calculator is the part where the
integer rewrite paid for itself immediately.
If you are building anything that takes a measurement from a human, do the normalisation at
the boundary. It is much harder to retrofit later.
0 Comments
Log in to join the conversation.No comments yet. Be the first to share your thoughts.