Skip to content

Commit

Permalink
fix floating point precision in floatyear_to_date (#1747)
Browse files Browse the repository at this point in the history
* fix floating point precision in floatyear_to_date

* small optimization, more tests

* fix test

* simplify type checking in floatyear_to_date
  • Loading branch information
pat-schmitt authored Oct 22, 2024
1 parent 3ec3cb0 commit 8de5db4
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 1 deletion.
10 changes: 10 additions & 0 deletions oggm/tests/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,16 @@ def test_floatyear_to_date(self):
r = utils.floatyear_to_date(yr)
assert r == (1998, 2)

# tests for floating point precision
yr = 1 + 1/12 - 1/12
r = utils.floatyear_to_date(yr)
assert r == (1, 1)

for i in range(12):
yr = 2000
r = utils.floatyear_to_date(yr + i / 12)
assert r == (yr, i + 1)

def test_date_to_floatyear(self):

r = utils.date_to_floatyear(0, 1)
Expand Down
15 changes: 14 additions & 1 deletion oggm/utils/_funcs.py
Original file line number Diff line number Diff line change
Expand Up @@ -690,6 +690,19 @@ def floatyear_to_date(yr):
if isinstance(yr, xr.DataArray):
yr = yr.values

# Ensure yr is a np.array, even for scalar values
yr = np.atleast_1d(yr).astype(np.float64)

# check if year is inside machine precision to next higher int
yr_ceil = np.ceil(yr)
yr = np.where(np.isclose(yr,
yr_ceil,
rtol=np.finfo(np.float64).eps,
atol=0
),
yr_ceil,
yr)

out_y, remainder = np.divmod(yr, 1)
out_y = out_y.astype(int)

Expand All @@ -700,7 +713,7 @@ def floatyear_to_date(yr):
np.round(month_exact),
np.floor(month_exact)).astype(int))

if (isinstance(yr, list) or isinstance(yr, np.ndarray)) and len(yr) == 1:
if yr.size == 1:
out_y = out_y.item()
out_m = out_m.item()

Expand Down

0 comments on commit 8de5db4

Please sign in to comment.