hgrecco / pint

Operate and manipulate physical quantities in Python
http://pint.readthedocs.org/
Other
2.4k stars 470 forks source link

Defining nonlinear unit conversions #1453

Open jesseishi opened 2 years ago

jesseishi commented 2 years ago

Hi, I'd like to be able to make a conversion from degrees to slope/grade in percent. Currently, naively that looks like:

from pint import UnitRegistry
ureg = UnitRegistry()
Q_ = ureg.Quantity
deg45 = Q_(45, "deg")
deg45.to("pct")

And yields <Quantity(78.5398163, 'percent')>. Which (I'm assuming) is because: 45 deg = 0.78 rad = 78%. I've read some other issues here and why this behavior is desired (radians being dimensionless and a base unit). But for my own work I'd like to define a new unit gradepct that takes an angle and calculates the grade in percent. I believe this is currently not possible because it is a trigonometric conversion: gradepct = tan(angle) * 100. Maybe it'd be nice if doing something like ureg.define('gradepct = lambda rad: math.tan(rad) * 100') were possible. But I'm very curious what you think of this.

jules-ch commented 2 years ago

You might get what you want using a custom Definition with a custom Converter. But for this I'd just use a function which use Quantity in degree & transform it to dimensionless Quantity.

Slopes & angle does not represent the same thing : Angle & a ratio. Quantity conversion should represent the same physical Quantity hence the name.

I'll try to show you an example for using a custom Converter

jesseishi commented 2 years ago

Nice, yeah making a function shouldn't be difficult. And thanks for your view on it.

Slopes & angle does not represent the same thing : Angle & a ratio. Quantity conversion should represent the same physical Quantity hence the name.

So strictly speaking it shouldn't work currently for deg to pct either... is that just a side-effect of rad being dimensionless (which I understand is desired).