Skip to content

Instantly share code, notes, and snippets.

@gvx
Created February 24, 2022 01:14
Show Gist options
  • Save gvx/739b2ce7f5243f8062b07692df5eb6c9 to your computer and use it in GitHub Desktop.
Save gvx/739b2ce7f5243f8062b07692df5eb6c9 to your computer and use it in GitHub Desktop.
Little script to verify https://xkcd.com/2585/
from functools import partial
from pint import UnitRegistry, Unit, Quantity
ureg = UnitRegistry()
def rounded_conversion(from_: Quantity, to: Unit) -> Quantity:
return Quantity(round(from_.to(to).magnitude), to)
def rounded_conversion_error(from_: Quantity, to: Unit) -> Quantity:
return rounded_conversion(from_, to).to(from_.units).to(from_.units)
def maximum_rounded_conversion_error(from_: Quantity, options: list[Unit]) -> Unit:
return max(options, key=partial(rounded_conversion_error, from_))
def worst_conversion(from_: Quantity, options: list[Unit]) -> Quantity:
worst_unit = maximum_rounded_conversion_error(from_, options)
return rounded_conversion(from_, worst_unit)
OPTIONS = [
ureg.mph,
ureg.m / ureg.s,
ureg.knots,
ureg.fathoms / ureg.s,
ureg.furlongs / ureg.min,
ureg.km / ureg.hour,
ureg.furlongs / ureg.hour,
ureg.yards / ureg.s,
]
value = 17. * ureg.mph
for _ in range(24):
value = worst_conversion(value, OPTIONS)
print(value)
print(value.to(ureg.mph))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment