"""Units carried through arithmetic: what pint refuses, a conversion chain, the Orbiter's factor, and dimensional analysis of a swinging weight.""" import sys from fractions import Fraction from pathlib import Path import pint import sympy as sp sys.path.insert(0, str(Path(__file__).resolve().parents[1])) from labkit import Q, const, versions # noqa: E402 print("computed:", versions()) print() print("1. Adding a length to a time") try: print(Q(3, "m") + Q(2, "s")) except pint.DimensionalityError as why: print(f" 3 m + 2 s -> refused: cannot convert from '{why.units1}' ({why.dim1}) to '{why.units2}' ({why.dim2})") print(f" 3 m * 2 s -> {Q(3, 'm') * Q(2, 's')} (multiplying is allowed: a new unit)") print(f" 3 m / 2 s -> {Q(3, 'm') / Q(2, 's')}") print() print("2. A chain of conversion factors, each equal to 1") speed = Q(100, "km/h") step1 = speed * (Q(1000, "m") / Q(1, "km")) step2 = step1 * (Q(1, "h") / Q(3600, "s")) print(f" 100 km/h x (1000 m / 1 km) x (1 h / 3600 s) = {step2.to('m/s').magnitude:.2f} m/s") print() print("3. The Mars Climate Orbiter's two units") lbf_s = Q(1, "lbf*s").to("N*s") print(f" 1 pound-force second = {lbf_s.magnitude:.3f} of the metric units the navigators expected") print(f" read as metric, every thruster firing came out {lbf_s.magnitude:.2f} times too small") print() print("4. Dimensional analysis: the swing time of a weight on a string") print(" candidates: length L [m], mass m [kg], gravity g [m/s^2]; wanted: time T [s]") a, b, c = sp.symbols("a b c") # L^a * m^b * g^c has metres^(a+c), kilograms^b, seconds^(-2c); match metres^0 kilograms^0 seconds^1 solution = sp.solve([a + c, b, -2 * c - 1], [a, b, c], dict=True)[0] print(f" metres: a + c = 0 kilograms: b = 0 seconds: -2c = 1") print(f" -> a = {solution[a]}, b = {solution[b]}, c = {solution[c]}: T is proportional to L^(1/2) g^(-1/2) = sqrt(L/g)") print(" the mass drops out entirely") for length in (Fraction(1, 4), Fraction(1), Fraction(4)): s = (Q(float(length), "m") / const.g_n) ** 0.5 print(f" L = {float(length):>4} m: sqrt(L/g) = {s.to('s').magnitude:.3f} s") print(" four times the length -> twice the time; a quarter of the length -> half the time")