Skip to content

Commit

Permalink
rewrite 4th pint feature as an example
Browse files Browse the repository at this point in the history
  • Loading branch information
TomNicholas committed Aug 30, 2022
1 parent 1b2b832 commit 0283833
Showing 1 changed file with 11 additions and 17 deletions.
28 changes: 11 additions & 17 deletions src/posts/introducing-pint-xarray/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -115,27 +115,21 @@ You also immediately get the key benefits of Pint:
<Quantity(2.6077643524162074e-11, 'parsec')>
```

4. You can specify that custom functions should expect certain units, and convert them if needed:
With these features, you can build code that automatically propagates units and converts them where necessary to stay consistent.
For example, the problem of the NASA orbiter could have been prevented by explicitly converting to the correct units at the start

```python
def jpl_trajectory_code(impulse):
"""This function will only compute the correct result if supplied input in units of Newton-seconds."""

if impulse.pint.units != "newton * second":
impulse = impulse.pint.to("Newton * seconds")

# do some rocket science
...
```python
def jpl_trajectory_code(impulse):

lockheed_impulse_value = xr.DataArray(5).pint.quantify("force_pounds * seconds")
# Defensively check units first
impulse = impulse.pint.to("Newton * seconds")

jpl_trajectory_code(lockheed_impulse_value)
```
# This function we called here will only compute the correct result if supplied input in units of Newton-seconds,
# but that's fine because we already converted the values to be in the correct units!
propagated_position = some_rocket_science(impulse)

```
Out:
pint.DimensionalityError
```
return propagated_position
```

Note: We are adding [new features](https://github.com/xarray-contrib/pint-xarray/pull/143) to make specifying the units of parameters of existing library functions more slick.

Expand Down

0 comments on commit 0283833

Please sign in to comment.