Metadata-Version: 2.5
Name: measfmt
Version: 0.1.0
Summary: Format real and complex measurements with uncertainties, SI prefixes, and correct rounding.
Author: Darwin Rescorla
License-Expression: MIT
License-File: LICENSE
Keywords: SI prefix,formatting,measurement,physics,significant figures,uncertainty
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Education
Classifier: Intended Audience :: Science/Research
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Topic :: Scientific/Engineering
Classifier: Topic :: Text Processing :: General
Requires-Python: >=3.9
Provides-Extra: test
Requires-Dist: pytest; extra == 'test'
Description-Content-Type: text/markdown

# measfmt

Format scientific measurements the way a lab report would: value and uncertainty rounded together, scaled with SI prefixes, with no dependencies.

```pycon
>>> from measfmt import fm
>>> fm("g", 9.81, 0.02, "m/s²")
'g = (9.81 ± 0.02) m/s²'
>>> fm("Length", 0.0012345, 0.00002, "m")
'Length = (1.23 ± 0.02) mm'
>>> fm("Pi", 3.14159265358979)
'Pi = 3.14159265358979'
```

## Installation

```sh
pip install measfmt
```

Requires Python 3.9 or newer. There are no runtime dependencies.

## Usage

`measfmt` exports one function under two names. They are the same object, so use whichever you prefer:

```pycon
>>> from measfmt import fm
>>> from measfmt import format_measurement
>>> fm is format_measurement
True
```

```python
fm(name, value, uncertainty=None, units="", *, scientific=False) -> str
```

| Argument      | Description                                                                              |
| ------------- | ---------------------------------------------------------------------------------------- |
| `name`        | Label shown on the left of the `=`.                                                      |
| `value`       | The measurement: `int`, `float`, `Decimal`, or `complex`.                                |
| `uncertainty` | Optional. Same kinds of number as `value`. Omit it or pass `None` to show the value only. |
| `units`       | Optional unit string appended to the result.                                             |
| `scientific`  | Keyword-only. If `True`, always use `× 10^n` instead of an SI prefix.                    |

### Rounding

The uncertainty is rounded to **one significant figure**, and the value is rounded to the same decimal place. Ties round half to even, and the arithmetic uses `Decimal`, so results are not affected by binary floating-point artifacts.

```pycon
>>> fm("x", 1.234, 0.096, "m")
'x = (1.2 ± 0.1) m'
>>> fm("x", 1.234, 0.0123, "m")
'x = (1.23 ± 0.01) m'
>>> fm("x", 9.99, 0.1, "m")   # rounding carries into the next digit
'x = (10.0 ± 0.1) m'
```

### SI prefixes

For recognized SI units, the value and uncertainty are scaled together by the prefix that keeps the number between 1 and 1000, from quecto (`q`, 10⁻³⁰) to quetta (`Q`, 10³⁰):

```pycon
>>> fm("x", 1234, 100, "m")
'x = (1.2 ± 0.1) km'
>>> fm("x", 0.0000015, 0.0000001, "s")
'x = (1.5 ± 0.1) µs'
>>> fm("x", 999, 1, "m")      # just below a boundary
'x = (999 ± 1) m'
>>> fm("x", 1000, 100, "m")   # exactly on a boundary
'x = (1.0 ± 0.1) km'
```

Prefixes are applied only to unprefixed SI base and derived units: `m g s A K mol cd rad sr Hz N Pa J W C V F Ω S Wb T H lm lx Bq Gy Sv kat`. Anything else (`kg`, `km`, `m/s`, `widgets`, or no unit at all) is scaled with a power of ten instead, because `measfmt` will not guess how to re-prefix a unit that already has a prefix or is compound:

```pycon
>>> fm("m", 1234, 100, "kg")
'm = (1.2 ± 0.1) × 10^3 kg'
>>> fm("x", 12, 1)
'x = (12 ± 1)'
```

Magnitudes outside the prefix range also fall back to powers of ten:

```pycon
>>> fm("x", 1e-33, 1e-34, "m")
'x = (1.0 ± 0.1) × 10^-33 m'
```

Pass `scientific=True` to force powers of ten even for prefixable units:

```pycon
>>> fm("x", 1234, 20, "m", scientific=True)
'x = (1.23 ± 0.02) × 10^3 m'
```

Values between 1 and 1000 (that is, those that need no scaling) are never given a `× 10^0` unless `scientific=True`.

### Optional uncertainty

If `uncertainty` is omitted or `None`, there is no `±` and no parentheses. The value is not rounded; it is shown as given, still scaled and with units:

```pycon
>>> fm("Pi", 3.14159265358979, None) == fm("Pi", 3.14159265358979)
True
>>> fm("Pi", 3.14159265358979)
'Pi = 3.14159265358979'
>>> fm("x", 1234.5, units="m")
'x = 1.2345 km'
```

Trailing zeros that come from `float` or `int` formatting (`1200.0`) are dropped. `Decimal` inputs keep their digits exactly, so `Decimal("1.500")` is shown as `1.500`.

### Zero and negative uncertainty

A **zero** uncertainty is valid and means the value is exact. It is printed as `± 0`, and the value is not rounded:

```pycon
>>> fm("c", 299792458, 0, "m/s")
'c = (2.99792458 ± 0) × 10^8 m/s'
>>> fm("x", 1.5, 0, "m")
'x = (1.5 ± 0) m'
```

A **negative** uncertainty is treated as its magnitude:

```pycon
>>> fm("x", 1.234, -0.096, "m")
'x = (1.2 ± 0.1) m'
```

### Complex numbers

Complex values are written as `(re ± u) + (im ± u)j`. The real and imaginary parts are each rounded to their own uncertainty but share a single scale, chosen from the larger part. The uncertainty can be complex, with its real and imaginary parts applying to the matching parts of the value. A real uncertainty applies to the real part only:

```pycon
>>> fm("z", complex(1.2, -3500), complex(0.1, 0.2), "m")
'z = ((0.0012 ± 0.0001) - (3.5000 ± 0.0002)j) km'
>>> fm("z", 1 + 2j, 0.1, "m")
'z = ((1.0 ± 0.1) + (2.0 ± 0)j) m'
```

Without an uncertainty, a complex value is parenthesized only when a scale or unit follows it:

```pycon
>>> fm("z", 1 + 2j)
'z = 1 + 2j'
>>> fm("z", 1 + 2j, None, "m")
'z = (1 + 2j) m'
```

A real value requires a real uncertainty; a complex uncertainty with a real value raises `TypeError`.

### Very large and very small numbers

Internally everything is converted to `Decimal` with enough precision for the inputs, so extreme magnitudes and extreme value-to-uncertainty ratios are handled exactly:

```pycon
>>> fm("x", 1.5e-300, 1e-301, "m")
'x = (1.5 ± 0.1) × 10^-300 m'
>>> fm("x", 10**1000, 10**999)
'x = (1.0 ± 0.1) × 10^1000'
```

### Non-finite values

`inf`, `-inf` and `nan` are passed through as `Infinity`, `-Infinity` and `NaN`:

```pycon
>>> fm("x", float("inf"), 0.1, "m")
'x = (Infinity ± 0.1) m'
>>> fm("x", 1, float("nan"), "m")
'x = (1 ± NaN) m'
```

### Errors

`TypeError` is raised if `value` or `uncertainty` is not a real or complex number, if `units` is not a string, or if `scientific` is not a `bool`.

## Development

```sh
pip install -e ".[test]"
pytest
```

## License

[MIT](LICENSE)
