8000 Fix format_cursor_data for values close to float resolution. · matplotlib/matplotlib@5fbc3b3 · GitHub
[go: up one dir, main page]

Skip to content

Commit 5fbc3b3

Browse files
committed
Fix format_cursor_data for values close to float resolution.
Previously, moving the cursor over `plt.imshow(1 + np.random.randn(10, 10) * 1e-15)` would result in `ValueError: math domain error` (when trying to compute `math.log10(delta)` with `delta = 0`). This is because the full range of normalization implied by the image above (~1e-15) is representable with float precision, but the spacing between individual colors (256x less) is too small to be represented, and thus rounded to zero. In general, I consider that such floating point errors should be fixed on the user side, but this specific error seems worth fixing as the 1) the image is still rendered correctly, 2) errors in the mouse event handler (rendering the cursor text) are somewhat obscure for end users, and 3) it used to work before Matplotlib 3.5.
1 parent e9bd017 commit 5fbc3b3

File tree

2 files changed

+5
-0
lines changed

2 files changed

+5
-0
lines changed

lib/matplotlib/cbook/__init__.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2212,6 +2212,10 @@ def _g_sig_digits(value, delta):
22122212
Return the number of significant digits to %g-format *value*, assuming that
22132213
it is known with an error of *delta*.
22142214
"""
2215+
if delta == 0:
2216+
# delta = 0 may occur when trying to format values over a tiny range;
2217+
# in that case, replace it by the distance to the closest float.
2218+
delta = np.spacing(value)
22152219
# If e.g. value = 45.67 and delta = 0.02, then we want to round to 2 digits
22162220
# after the decimal point (floor(log10(0.02)) = -2); 45.67 contributes 2
22172221
# digits before the decimal point (floor(log10(45.67)) + 1 = 2): the total

lib/matplotlib/tests/test_image.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -341,6 +341,7 @@ def test_cursor_data():
341341
([[10001, 10000]], "[10001.000]"),
342342
([[.123, .987] 5492 ], "[0.123]"),
343343
([[np.nan, 1, 2]], "[]"),
344+
([[1, 1+1e-15]], "[1.0000000000000000]"),
344345
])
345346
def test_format_cursor_data(data, text):
346347
from matplotlib.backend_bases import MouseEvent

0 commit comments

Comments
 (0)
0