measfmt 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- measfmt/__init__.py +305 -0
- measfmt-0.1.0.dist-info/METADATA +210 -0
- measfmt-0.1.0.dist-info/RECORD +5 -0
- measfmt-0.1.0.dist-info/WHEEL +4 -0
- measfmt-0.1.0.dist-info/licenses/LICENSE +21 -0
measfmt/__init__.py
ADDED
|
@@ -0,0 +1,305 @@
|
|
|
1
|
+
"""Format real and complex measurements with their uncertainties."""
|
|
2
|
+
|
|
3
|
+
from decimal import ROUND_HALF_EVEN, Decimal, localcontext
|
|
4
|
+
from numbers import Complex, Real
|
|
5
|
+
|
|
6
|
+
__all__ = ["fm", "format_measurement"]
|
|
7
|
+
|
|
8
|
+
__version__ = "0.1.0"
|
|
9
|
+
|
|
10
|
+
# List of SI prefixes and their corresponding powers of ten.
|
|
11
|
+
_PREFIXES = {
|
|
12
|
+
-30: "q",
|
|
13
|
+
-27: "r",
|
|
14
|
+
-24: "y",
|
|
15
|
+
-21: "z",
|
|
16
|
+
-18: "a",
|
|
17
|
+
-15: "f",
|
|
18
|
+
-12: "p",
|
|
19
|
+
-9: "n",
|
|
20
|
+
-6: "µ",
|
|
21
|
+
-3: "m",
|
|
22
|
+
0: "",
|
|
23
|
+
3: "k",
|
|
24
|
+
6: "M",
|
|
25
|
+
9: "G",
|
|
26
|
+
12: "T",
|
|
27
|
+
15: "P",
|
|
28
|
+
18: "E",
|
|
29
|
+
21: "Z",
|
|
30
|
+
24: "Y",
|
|
31
|
+
27: "R",
|
|
32
|
+
30: "Q",
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
# Units like kilograms and compound units are deliberately excluded: they already
|
|
36
|
+
# contain a prefix or require interpreting the structure of the unit.
|
|
37
|
+
_PREFIXABLE_UNITS = frozenset(
|
|
38
|
+
{
|
|
39
|
+
"m",
|
|
40
|
+
"g",
|
|
41
|
+
"s",
|
|
42
|
+
"A",
|
|
43
|
+
"K",
|
|
44
|
+
"mol",
|
|
45
|
+
"cd",
|
|
46
|
+
"rad",
|
|
47
|
+
"sr",
|
|
48
|
+
"Hz",
|
|
49
|
+
"N",
|
|
50
|
+
"Pa",
|
|
51
|
+
"J",
|
|
52
|
+
"W",
|
|
53
|
+
"C",
|
|
54
|
+
"V",
|
|
55
|
+
"F",
|
|
56
|
+
"Ω",
|
|
57
|
+
"S",
|
|
58
|
+
"Wb",
|
|
59
|
+
"T",
|
|
60
|
+
"H",
|
|
61
|
+
"lm",
|
|
62
|
+
"lx",
|
|
63
|
+
"Bq",
|
|
64
|
+
"Gy",
|
|
65
|
+
"Sv",
|
|
66
|
+
"kat",
|
|
67
|
+
}
|
|
68
|
+
)
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _decimal(value):
|
|
72
|
+
"""Convert a real numeric component to a sufficiently precise ``Decimal``.
|
|
73
|
+
|
|
74
|
+
Raises ``TypeError`` when ``value`` is not one of the supported real
|
|
75
|
+
numeric types.
|
|
76
|
+
"""
|
|
77
|
+
if not isinstance(value, (Real, Decimal)):
|
|
78
|
+
raise TypeError("value and uncertainty components must be real numbers")
|
|
79
|
+
return Decimal(str(value))
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _is_complex(value):
|
|
83
|
+
"""Return whether ``value`` is a non-real complex number."""
|
|
84
|
+
return isinstance(value, Complex) and not isinstance(value, Real)
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def _components(value, uncertainty):
|
|
88
|
+
"""Separate a real or complex measurement into Decimal components.
|
|
89
|
+
|
|
90
|
+
Complex values and uncertainties contribute real and imaginary components. A
|
|
91
|
+
real-valued measurement must have a real-valued uncertainty. When
|
|
92
|
+
``uncertainty`` is ``None`` the returned uncertainties are all ``None``.
|
|
93
|
+
"""
|
|
94
|
+
if uncertainty is None:
|
|
95
|
+
parts = (value.real, value.imag) if _is_complex(value) else (value,)
|
|
96
|
+
return _is_complex(value), tuple(_decimal(p) for p in parts), (None,) * len(parts)
|
|
97
|
+
is_complex = _is_complex(value)
|
|
98
|
+
if is_complex:
|
|
99
|
+
if not isinstance(uncertainty, (Complex, Decimal)):
|
|
100
|
+
raise TypeError("uncertainty must be a real or complex number")
|
|
101
|
+
return (
|
|
102
|
+
True,
|
|
103
|
+
(_decimal(value.real), _decimal(value.imag)),
|
|
104
|
+
(_decimal(uncertainty.real), _decimal(uncertainty.imag)),
|
|
105
|
+
)
|
|
106
|
+
if _is_complex(uncertainty):
|
|
107
|
+
raise TypeError("a real value requires a real uncertainty")
|
|
108
|
+
return False, (_decimal(value),), (_decimal(uncertainty),)
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def _round_component(value, uncertainty):
|
|
112
|
+
"""Round a component and its uncertainty to the uncertainty's decimal place.
|
|
113
|
+
|
|
114
|
+
Finite, nonzero uncertainties are rounded to one significant figure. The
|
|
115
|
+
returned value is also quantized at that figure's decimal place; the third
|
|
116
|
+
item is the decimal exponent used for shared scaling and fixed-point output.
|
|
117
|
+
"""
|
|
118
|
+
if uncertainty is None or not uncertainty.is_finite() or uncertainty.is_zero():
|
|
119
|
+
return value, uncertainty, None
|
|
120
|
+
|
|
121
|
+
uncertainty = uncertainty.copy_abs()
|
|
122
|
+
exponent = uncertainty.adjusted()
|
|
123
|
+
quantum = Decimal(1).scaleb(exponent)
|
|
124
|
+
rounded_uncertainty = uncertainty.quantize(quantum, rounding=ROUND_HALF_EVEN)
|
|
125
|
+
if rounded_uncertainty.adjusted() > exponent:
|
|
126
|
+
exponent = rounded_uncertainty.adjusted()
|
|
127
|
+
quantum = Decimal(1).scaleb(exponent)
|
|
128
|
+
rounded_uncertainty = uncertainty.quantize(quantum, rounding=ROUND_HALF_EVEN)
|
|
129
|
+
if value.is_finite():
|
|
130
|
+
value = value.quantize(quantum, rounding=ROUND_HALF_EVEN)
|
|
131
|
+
return value, rounded_uncertainty, exponent
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def _magnitude(values):
|
|
135
|
+
"""Return the largest absolute finite value, or zero if none is finite.
|
|
136
|
+
|
|
137
|
+
``None`` entries (missing uncertainties) are ignored.
|
|
138
|
+
"""
|
|
139
|
+
finite = [
|
|
140
|
+
value.copy_abs()
|
|
141
|
+
for value in values
|
|
142
|
+
if value is not None and value.is_finite()
|
|
143
|
+
]
|
|
144
|
+
return max(finite, default=Decimal(0))
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def _format_number(value, decimals=None):
|
|
148
|
+
"""Format a Decimal with fixed decimal places or a plain Decimal string.
|
|
149
|
+
|
|
150
|
+
When ``decimals`` is ``None``, finite values are emitted without trailing
|
|
151
|
+
rounding zeros and non-finite values are preserved by ``Decimal``'s string
|
|
152
|
+
representation.
|
|
153
|
+
"""
|
|
154
|
+
if value.is_zero():
|
|
155
|
+
if decimals is None:
|
|
156
|
+
return "0"
|
|
157
|
+
value = value.copy_abs()
|
|
158
|
+
if not value.is_finite() or decimals is None:
|
|
159
|
+
return str(value) if not value.is_finite() else format(value, "f")
|
|
160
|
+
return f"{value:.{decimals}f}"
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def _format_component(value, uncertainty, precision, scale):
|
|
164
|
+
"""Scale a value and optional uncertainty, then format them as one component."""
|
|
165
|
+
value = value.scaleb(-scale)
|
|
166
|
+
decimals = None if precision is None else max(scale - precision, 0)
|
|
167
|
+
if uncertainty is None:
|
|
168
|
+
return _format_number(value, decimals)
|
|
169
|
+
uncertainty = uncertainty.scaleb(-scale)
|
|
170
|
+
return f"{_format_number(value, decimals)} ± {_format_number(uncertainty, decimals)}"
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def format_measurement(name, value, uncertainty=None, units="", *, scientific=False):
|
|
174
|
+
"""Format a measurement, scaling its value and uncertainty together.
|
|
175
|
+
|
|
176
|
+
Recognized unprefixed SI units use engineering-scale prefixes. Other units
|
|
177
|
+
and dimensionless measurements use scientific notation when scaling is
|
|
178
|
+
needed, as do magnitudes outside the SI prefix range. Set
|
|
179
|
+
``scientific=True`` to always use a power of ten. Finite, nonzero
|
|
180
|
+
uncertainties are rounded to one significant figure, and each component
|
|
181
|
+
is rounded to the same decimal place as its uncertainty. Complex values
|
|
182
|
+
share a scale based on their larger component; a real uncertainty applies only
|
|
183
|
+
to the real component. Negative uncertainties are treated as their
|
|
184
|
+
magnitude. The complete measurement is parenthesized so any scale and
|
|
185
|
+
unit apply to both the value and its uncertainty.
|
|
186
|
+
|
|
187
|
+
When ``uncertainty`` is omitted or ``None``, the value is shown exactly as
|
|
188
|
+
given (no rounding) with no ``±`` part and no parentheses, e.g.
|
|
189
|
+
``Pi = 3.14159``. Scaling and units still apply, and a complex value is
|
|
190
|
+
parenthesized only when a scale or unit follows it.
|
|
191
|
+
|
|
192
|
+
Args:
|
|
193
|
+
name: The measurement name used in the ``name = value`` output.
|
|
194
|
+
value: A real or complex numeric measurement.
|
|
195
|
+
uncertainty: Optional matching real or complex uncertainty. For a real
|
|
196
|
+
value, the uncertainty must be real; real uncertainties describe
|
|
197
|
+
only the real component of a complex value. A zero uncertainty is
|
|
198
|
+
valid and means the value is exact.
|
|
199
|
+
units: Optional unit string appended to the formatted measurement.
|
|
200
|
+
scientific: When true, always express the scale as a power of ten.
|
|
201
|
+
|
|
202
|
+
Returns:
|
|
203
|
+
A human-readable measurement string.
|
|
204
|
+
|
|
205
|
+
Raises:
|
|
206
|
+
TypeError: If units, scientific, or the numeric components have invalid types.
|
|
207
|
+
"""
|
|
208
|
+
if not isinstance(units, str):
|
|
209
|
+
raise TypeError("units must be a string")
|
|
210
|
+
if not isinstance(scientific, bool):
|
|
211
|
+
raise TypeError("scientific must be a bool")
|
|
212
|
+
is_complex, values, uncertainties = _components(value, uncertainty)
|
|
213
|
+
|
|
214
|
+
# Preserve enough Decimal digits for both extreme exponents and small
|
|
215
|
+
# uncertainties, because quantization otherwise depends on context precision.
|
|
216
|
+
finite = [
|
|
217
|
+
number
|
|
218
|
+
for number in values + uncertainties
|
|
219
|
+
if number is not None and number.is_finite() and not number.is_zero()
|
|
220
|
+
]
|
|
221
|
+
if finite:
|
|
222
|
+
highest = max(number.adjusted() for number in finite)
|
|
223
|
+
lowest = min(number.as_tuple().exponent for number in finite)
|
|
224
|
+
precision = max(28, highest - lowest + 10)
|
|
225
|
+
else:
|
|
226
|
+
precision = 28
|
|
227
|
+
|
|
228
|
+
with localcontext() as context:
|
|
229
|
+
context.prec = precision
|
|
230
|
+
if uncertainty is None and not isinstance(value, Decimal):
|
|
231
|
+
# Without an uncertainty there is no precision to honor, so drop
|
|
232
|
+
# artifacts such as the trailing zero of ``1200.0``. Decimal inputs
|
|
233
|
+
# keep their digits because trailing zeros can be intentional.
|
|
234
|
+
values = tuple(number.normalize() for number in values)
|
|
235
|
+
# Quantize each component against its own uncertainty, then use the
|
|
236
|
+
# largest rounded component to select a scale shared by all components.
|
|
237
|
+
rounded = tuple(_round_component(v, e) for v, e in zip(values, uncertainties))
|
|
238
|
+
rounded_values = tuple(component[0] for component in rounded)
|
|
239
|
+
magnitude = _magnitude(values)
|
|
240
|
+
if magnitude.is_zero() and all(
|
|
241
|
+
value.is_finite() and value.is_zero() for value in values
|
|
242
|
+
):
|
|
243
|
+
magnitude = _magnitude(uncertainties)
|
|
244
|
+
|
|
245
|
+
use_prefix = not scientific and units in _PREFIXABLE_UNITS
|
|
246
|
+
# Prefix units use multiples of three; all other units and dimensionless
|
|
247
|
+
# values select powers of ten without prefix-oriented rounding.
|
|
248
|
+
step = 3 if use_prefix else 1
|
|
249
|
+
exponent = (
|
|
250
|
+
(magnitude.adjusted() // step) * step if not magnitude.is_zero() else 0
|
|
251
|
+
)
|
|
252
|
+
|
|
253
|
+
# Rounding can carry the controlling value into a different scale.
|
|
254
|
+
rounded_magnitude = _magnitude(rounded_values)
|
|
255
|
+
if not rounded_magnitude.is_zero():
|
|
256
|
+
exponent = (rounded_magnitude.adjusted() // step) * step
|
|
257
|
+
|
|
258
|
+
# Outside the supported SI-prefix range, fall back to scientific notation
|
|
259
|
+
# using the exact resulting component magnitude instead.
|
|
260
|
+
if use_prefix and exponent not in _PREFIXES:
|
|
261
|
+
use_prefix = False
|
|
262
|
+
exponent = (
|
|
263
|
+
rounded_magnitude.adjusted()
|
|
264
|
+
if not rounded_magnitude.is_zero()
|
|
265
|
+
else (magnitude.adjusted() if not magnitude.is_zero() else 0)
|
|
266
|
+
)
|
|
267
|
+
|
|
268
|
+
if not scientific and not use_prefix and 0 <= exponent < 3:
|
|
269
|
+
exponent = 0
|
|
270
|
+
|
|
271
|
+
parts = [
|
|
272
|
+
_format_component(component, uncertainty, place, exponent)
|
|
273
|
+
for component, uncertainty, place in rounded
|
|
274
|
+
]
|
|
275
|
+
if is_complex:
|
|
276
|
+
# Render the imaginary component separately so its sign is not lost
|
|
277
|
+
# and its magnitude, uncertainty, and scale remain self-consistent.
|
|
278
|
+
imag_negative = (
|
|
279
|
+
rounded_values[1].is_signed() and not rounded_values[1].is_zero()
|
|
280
|
+
)
|
|
281
|
+
imag_value, imag_uncertainty, imag_place = rounded[1]
|
|
282
|
+
imag_text = _format_component(
|
|
283
|
+
imag_value.copy_abs(), imag_uncertainty, imag_place, exponent
|
|
284
|
+
)
|
|
285
|
+
sign = "-" if imag_negative else "+"
|
|
286
|
+
if uncertainty is None:
|
|
287
|
+
text = f"{parts[0]} {sign} {imag_text}j"
|
|
288
|
+
else:
|
|
289
|
+
text = f"({parts[0]}) {sign} ({imag_text})j"
|
|
290
|
+
else:
|
|
291
|
+
text = parts[0]
|
|
292
|
+
|
|
293
|
+
if use_prefix:
|
|
294
|
+
suffix = f" {_PREFIXES[exponent]}{units}"
|
|
295
|
+
elif scientific or exponent:
|
|
296
|
+
suffix = f" × 10^{exponent}" + (f" {units}" if units else "")
|
|
297
|
+
else:
|
|
298
|
+
suffix = f" {units}" if units else ""
|
|
299
|
+
|
|
300
|
+
if uncertainty is not None or (is_complex and suffix):
|
|
301
|
+
text = f"({text})"
|
|
302
|
+
return f"{name} = {text}{suffix}"
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
fm = format_measurement
|
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: measfmt
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Format real and complex measurements with uncertainties, SI prefixes, and correct rounding.
|
|
5
|
+
Author: Darwin Rescorla
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
License-File: LICENSE
|
|
8
|
+
Keywords: SI prefix,formatting,measurement,physics,significant figures,uncertainty
|
|
9
|
+
Classifier: Development Status :: 4 - Beta
|
|
10
|
+
Classifier: Intended Audience :: Education
|
|
11
|
+
Classifier: Intended Audience :: Science/Research
|
|
12
|
+
Classifier: Operating System :: OS Independent
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
15
|
+
Classifier: Topic :: Scientific/Engineering
|
|
16
|
+
Classifier: Topic :: Text Processing :: General
|
|
17
|
+
Requires-Python: >=3.9
|
|
18
|
+
Provides-Extra: test
|
|
19
|
+
Requires-Dist: pytest; extra == 'test'
|
|
20
|
+
Description-Content-Type: text/markdown
|
|
21
|
+
|
|
22
|
+
# measfmt
|
|
23
|
+
|
|
24
|
+
Format scientific measurements the way a lab report would: value and uncertainty rounded together, scaled with SI prefixes, with no dependencies.
|
|
25
|
+
|
|
26
|
+
```pycon
|
|
27
|
+
>>> from measfmt import fm
|
|
28
|
+
>>> fm("g", 9.81, 0.02, "m/s²")
|
|
29
|
+
'g = (9.81 ± 0.02) m/s²'
|
|
30
|
+
>>> fm("Length", 0.0012345, 0.00002, "m")
|
|
31
|
+
'Length = (1.23 ± 0.02) mm'
|
|
32
|
+
>>> fm("Pi", 3.14159265358979)
|
|
33
|
+
'Pi = 3.14159265358979'
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
## Installation
|
|
37
|
+
|
|
38
|
+
```sh
|
|
39
|
+
pip install measfmt
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
Requires Python 3.9 or newer. There are no runtime dependencies.
|
|
43
|
+
|
|
44
|
+
## Usage
|
|
45
|
+
|
|
46
|
+
`measfmt` exports one function under two names. They are the same object, so use whichever you prefer:
|
|
47
|
+
|
|
48
|
+
```pycon
|
|
49
|
+
>>> from measfmt import fm
|
|
50
|
+
>>> from measfmt import format_measurement
|
|
51
|
+
>>> fm is format_measurement
|
|
52
|
+
True
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
```python
|
|
56
|
+
fm(name, value, uncertainty=None, units="", *, scientific=False) -> str
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
| Argument | Description |
|
|
60
|
+
| ------------- | ---------------------------------------------------------------------------------------- |
|
|
61
|
+
| `name` | Label shown on the left of the `=`. |
|
|
62
|
+
| `value` | The measurement: `int`, `float`, `Decimal`, or `complex`. |
|
|
63
|
+
| `uncertainty` | Optional. Same kinds of number as `value`. Omit it or pass `None` to show the value only. |
|
|
64
|
+
| `units` | Optional unit string appended to the result. |
|
|
65
|
+
| `scientific` | Keyword-only. If `True`, always use `× 10^n` instead of an SI prefix. |
|
|
66
|
+
|
|
67
|
+
### Rounding
|
|
68
|
+
|
|
69
|
+
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.
|
|
70
|
+
|
|
71
|
+
```pycon
|
|
72
|
+
>>> fm("x", 1.234, 0.096, "m")
|
|
73
|
+
'x = (1.2 ± 0.1) m'
|
|
74
|
+
>>> fm("x", 1.234, 0.0123, "m")
|
|
75
|
+
'x = (1.23 ± 0.01) m'
|
|
76
|
+
>>> fm("x", 9.99, 0.1, "m") # rounding carries into the next digit
|
|
77
|
+
'x = (10.0 ± 0.1) m'
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
### SI prefixes
|
|
81
|
+
|
|
82
|
+
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³⁰):
|
|
83
|
+
|
|
84
|
+
```pycon
|
|
85
|
+
>>> fm("x", 1234, 100, "m")
|
|
86
|
+
'x = (1.2 ± 0.1) km'
|
|
87
|
+
>>> fm("x", 0.0000015, 0.0000001, "s")
|
|
88
|
+
'x = (1.5 ± 0.1) µs'
|
|
89
|
+
>>> fm("x", 999, 1, "m") # just below a boundary
|
|
90
|
+
'x = (999 ± 1) m'
|
|
91
|
+
>>> fm("x", 1000, 100, "m") # exactly on a boundary
|
|
92
|
+
'x = (1.0 ± 0.1) km'
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
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:
|
|
96
|
+
|
|
97
|
+
```pycon
|
|
98
|
+
>>> fm("m", 1234, 100, "kg")
|
|
99
|
+
'm = (1.2 ± 0.1) × 10^3 kg'
|
|
100
|
+
>>> fm("x", 12, 1)
|
|
101
|
+
'x = (12 ± 1)'
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
Magnitudes outside the prefix range also fall back to powers of ten:
|
|
105
|
+
|
|
106
|
+
```pycon
|
|
107
|
+
>>> fm("x", 1e-33, 1e-34, "m")
|
|
108
|
+
'x = (1.0 ± 0.1) × 10^-33 m'
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
Pass `scientific=True` to force powers of ten even for prefixable units:
|
|
112
|
+
|
|
113
|
+
```pycon
|
|
114
|
+
>>> fm("x", 1234, 20, "m", scientific=True)
|
|
115
|
+
'x = (1.23 ± 0.02) × 10^3 m'
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
Values between 1 and 1000 (that is, those that need no scaling) are never given a `× 10^0` unless `scientific=True`.
|
|
119
|
+
|
|
120
|
+
### Optional uncertainty
|
|
121
|
+
|
|
122
|
+
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:
|
|
123
|
+
|
|
124
|
+
```pycon
|
|
125
|
+
>>> fm("Pi", 3.14159265358979, None) == fm("Pi", 3.14159265358979)
|
|
126
|
+
True
|
|
127
|
+
>>> fm("Pi", 3.14159265358979)
|
|
128
|
+
'Pi = 3.14159265358979'
|
|
129
|
+
>>> fm("x", 1234.5, units="m")
|
|
130
|
+
'x = 1.2345 km'
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
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`.
|
|
134
|
+
|
|
135
|
+
### Zero and negative uncertainty
|
|
136
|
+
|
|
137
|
+
A **zero** uncertainty is valid and means the value is exact. It is printed as `± 0`, and the value is not rounded:
|
|
138
|
+
|
|
139
|
+
```pycon
|
|
140
|
+
>>> fm("c", 299792458, 0, "m/s")
|
|
141
|
+
'c = (2.99792458 ± 0) × 10^8 m/s'
|
|
142
|
+
>>> fm("x", 1.5, 0, "m")
|
|
143
|
+
'x = (1.5 ± 0) m'
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
A **negative** uncertainty is treated as its magnitude:
|
|
147
|
+
|
|
148
|
+
```pycon
|
|
149
|
+
>>> fm("x", 1.234, -0.096, "m")
|
|
150
|
+
'x = (1.2 ± 0.1) m'
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
### Complex numbers
|
|
154
|
+
|
|
155
|
+
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:
|
|
156
|
+
|
|
157
|
+
```pycon
|
|
158
|
+
>>> fm("z", complex(1.2, -3500), complex(0.1, 0.2), "m")
|
|
159
|
+
'z = ((0.0012 ± 0.0001) - (3.5000 ± 0.0002)j) km'
|
|
160
|
+
>>> fm("z", 1 + 2j, 0.1, "m")
|
|
161
|
+
'z = ((1.0 ± 0.1) + (2.0 ± 0)j) m'
|
|
162
|
+
```
|
|
163
|
+
|
|
164
|
+
Without an uncertainty, a complex value is parenthesized only when a scale or unit follows it:
|
|
165
|
+
|
|
166
|
+
```pycon
|
|
167
|
+
>>> fm("z", 1 + 2j)
|
|
168
|
+
'z = 1 + 2j'
|
|
169
|
+
>>> fm("z", 1 + 2j, None, "m")
|
|
170
|
+
'z = (1 + 2j) m'
|
|
171
|
+
```
|
|
172
|
+
|
|
173
|
+
A real value requires a real uncertainty; a complex uncertainty with a real value raises `TypeError`.
|
|
174
|
+
|
|
175
|
+
### Very large and very small numbers
|
|
176
|
+
|
|
177
|
+
Internally everything is converted to `Decimal` with enough precision for the inputs, so extreme magnitudes and extreme value-to-uncertainty ratios are handled exactly:
|
|
178
|
+
|
|
179
|
+
```pycon
|
|
180
|
+
>>> fm("x", 1.5e-300, 1e-301, "m")
|
|
181
|
+
'x = (1.5 ± 0.1) × 10^-300 m'
|
|
182
|
+
>>> fm("x", 10**1000, 10**999)
|
|
183
|
+
'x = (1.0 ± 0.1) × 10^1000'
|
|
184
|
+
```
|
|
185
|
+
|
|
186
|
+
### Non-finite values
|
|
187
|
+
|
|
188
|
+
`inf`, `-inf` and `nan` are passed through as `Infinity`, `-Infinity` and `NaN`:
|
|
189
|
+
|
|
190
|
+
```pycon
|
|
191
|
+
>>> fm("x", float("inf"), 0.1, "m")
|
|
192
|
+
'x = (Infinity ± 0.1) m'
|
|
193
|
+
>>> fm("x", 1, float("nan"), "m")
|
|
194
|
+
'x = (1 ± NaN) m'
|
|
195
|
+
```
|
|
196
|
+
|
|
197
|
+
### Errors
|
|
198
|
+
|
|
199
|
+
`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`.
|
|
200
|
+
|
|
201
|
+
## Development
|
|
202
|
+
|
|
203
|
+
```sh
|
|
204
|
+
pip install -e ".[test]"
|
|
205
|
+
pytest
|
|
206
|
+
```
|
|
207
|
+
|
|
208
|
+
## License
|
|
209
|
+
|
|
210
|
+
[MIT](LICENSE)
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
measfmt/__init__.py,sha256=03BuJ_IZrakw6Shjx7dPPiSqP5ACn8STpamDBCgZGro,11362
|
|
2
|
+
measfmt-0.1.0.dist-info/METADATA,sha256=p_iBQhFf8b3d3nq2YhB1be7PgRVQiOh7WlJNNkDgD3s,6833
|
|
3
|
+
measfmt-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
4
|
+
measfmt-0.1.0.dist-info/licenses/LICENSE,sha256=EeqCxXMlKDX77M7v2Syj-ngMGJW9pSj6VO3rq6Ka8mY,1072
|
|
5
|
+
measfmt-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Darwin Rescorla
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|