Skip to content

Calculating ratios is awkward and fragile #126

Open
@berkowski

Description

@berkowski

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions