printfn / fend

Arbitrary-precision unit-aware calculator
https://printfn.github.io/fend
MIT License
633 stars 51 forks source link

Feature request: Represent Hz as 1/s #247

Open monban opened 10 months ago

monban commented 10 months ago

Example use-case: I would like to know the approximate length of antenna for a 145MHz (amateur radio) signal. The formula for wavelength is

{\lambda} = \frac{v}{f}

Where f is the frequency in Hertz, which is a unit of cycles / second. Since we're dealing with electromagnetic radiation, velocity v=c (not accounting for velocity factor, which we will set aside for the purposes of this discussion). Written out, this means the full formula should look like:

{\lambda} = \frac{299,792,458m/s}{145*10^6/s}

fend is smart enough to know that the seconds can cancel out, leaving us with

{\lambda} = \frac{299,792,458m}{145*10^6} \approx 2.0675341931m

Expected behaviour:

> c/145MHz
approx. 2.0675341931 m

Actual behaviour:

> c/145MHz
approx. 2067534.1931034482 m MHz / s

For now, I've been using this workaround:

> c/(145e6/s)
approx. 2.0675341931 m

I would much prefer if fend simply understood that nHz represents n/s (and of course si prefixes like kHz and MHz represent $n(10^3)$ and $n(10^6)$ respectively) so that equations like solving for wavelength would simply come out correctly.

printfn commented 10 months ago

Another workaround is c/(145MHz) to m.

But yes, this is definitely an issue that should be fixed.

dpeachpeach commented 9 months ago

hi, if you're looking for contributors on this issue I wouldn't mind taking a shot at it!

printfn commented 9 months ago

Sure, but I think it will be a bit tricky to fix.

This issue is the result of two separate bugs in fend: on one hand, fend's operator precedence rules cause inputs like c/145MHz to be parsed in an unexpected way, as (c/145) MHz instead of c / (145MHz). This will need a change to the parsing code without breaking other behaviours that we want to preserve. See #76 for details.

The second half of this bug is that unit simplification should be extended. Currently fend will perform simplifications like m^2 / m -> m, but not e.g. m s^-1 MHz^-1 -> m. #150 also related to this.

dpeachpeach commented 9 months ago

Thanks! It looks like a better starting point would be taking a look at #150. I can jump over to that thread first.

printfn commented 8 months ago

I've pushed a change that implements better unit simplification, which resolves part of this issue. Units like m s^-1 MHz^-1 now get simplified to meters.

> c / (145MHz)
approx. 2.0675341931 meters