Skip to content

Commit 5494000

Browse files
committed
fix(truncate): add machine-consistent behaviour for undefined NaN error
Closes #280
1 parent cb6c292 commit 5494000

File tree

2 files changed

+23
-6
lines changed

2 files changed

+23
-6
lines changed

caput/truncate.pyx

+14
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,14 @@ def bit_truncate_float(float val, float err):
6464
-------
6565
val
6666
The truncated value.
67+
68+
Raises
69+
------
70+
ValueError
71+
If `err` is a NaN.
6772
"""
73+
if err != err:
74+
raise ValueError(f"Error {err} is invalid.")
6875

6976
return _bit_truncate_float(val, err)
7077

@@ -83,7 +90,14 @@ def bit_truncate_double(double val, double err):
8390
-------
8491
val
8592
The truncated value.
93+
94+
Raises
95+
------
96+
ValueError
97+
If `err` is a NaN.
8698
"""
99+
if err != err:
100+
raise ValueError(f"Error {err} is invalid.")
87101

88102
return _bit_truncate_double(val, err)
89103

tests/test_truncate.py

+9-6
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import numpy as np
2+
import pytest
23

34
from caput import truncate
45

@@ -58,21 +59,23 @@ def test_truncate_float():
5859
assert truncate.bit_truncate_double(32.121, -1) == 0
5960
assert truncate.bit_truncate_float(32.121, np.inf) == 0
6061
assert truncate.bit_truncate_double(32.121, np.inf) == 0
61-
assert truncate.bit_truncate_float(32.121, np.nan) == 0
62-
assert truncate.bit_truncate_double(32.121, np.nan) == 0
6362
assert truncate.bit_truncate_float(np.inf, 1) == np.inf
6463
assert truncate.bit_truncate_double(np.inf, 1) == np.inf
6564
assert np.isnan(truncate.bit_truncate_float(np.nan, 1))
6665
assert np.isnan(truncate.bit_truncate_double(np.nan, 1))
66+
6767
assert truncate.bit_truncate_float(np.inf, np.inf) == 0
6868
assert truncate.bit_truncate_double(np.inf, np.inf) == 0
69-
assert truncate.bit_truncate_float(np.inf, np.nan) == 0
70-
assert truncate.bit_truncate_double(np.inf, np.nan) == 0
71-
assert truncate.bit_truncate_float(np.nan, np.nan) == 0
72-
assert truncate.bit_truncate_double(np.nan, np.nan) == 0
7369
assert truncate.bit_truncate_float(np.nan, np.inf) == 0
7470
assert truncate.bit_truncate_double(np.nan, np.inf) == 0
7571

72+
# Test that an error is raised when `err` is `NaN`
73+
with pytest.raises(ValueError):
74+
truncate.bit_truncate_float(32.121, np.nan)
75+
76+
with pytest.raises(ValueError):
77+
truncate.bit_truncate_double(32.121, np.nan)
78+
7679

7780
def test_truncate_array():
7881
assert (

0 commit comments

Comments
 (0)