embedded-time icon indicating copy to clipboard operation
embedded-time copied to clipboard

Calculating ratios is awkward and fragile

Open berkowski opened this issue 3 years ago • 0 comments

I often need to calculate the ratio of two values with the same units. For example,

let a = Kilohertz(200u32);
let b = Kilohertz(100u32);

// I'd like to do this
let ratio = a / b;

// Instead I need to do this:
let ratio = a.0 / b.0

The workaround is fragile. What happens if the code changes:

let a = Hertz(200u32);
let b = Kilohertz(100u32);

// This line is now incorrect without changing
let ratio = a.0 / b.0

Having to pull the underlying value out of the type defeats the whole purpose of having these unit types to begin with. Am I missing something? Is there a more 'correct' way to calculate the ratio?

I thought the limitation would be in the Fractional struct, but I see it's just a wrapper around num_rational::Rational. Why not just use the upstream structure instead? It supports arithmetic ops already.

berkowski avatar May 28 '22 22:05 berkowski