Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix floating point precision in floatyear_to_date #1747

Merged
merged 4 commits into from
Oct 22, 2024
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
17 changes: 17 additions & 0 deletions oggm/utils/_funcs.py
Original file line number Diff line number Diff line change
Expand Up @@ -690,6 +690,23 @@ def floatyear_to_date(yr):
if isinstance(yr, xr.DataArray):
yr = yr.values

if isinstance(yr, (int, float)):
yr = np.array([yr], dtype=np.float64)

if ((isinstance(yr, np.ndarray) or
isinstance(yr, np.generic)) and yr.size == 1):
yr = np.array([yr], dtype=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 Down