Skip to content

Fix integer overflow in geographic distance features - #1099

Merged
solegalli merged 2 commits into
feature-engine:narwhals-migrationfrom
aalquwayfili:fix-geodistance-integer-overflow
Nov 29, 2026
Merged

solegalli merged 2 commits into
feature-engine:narwhals-migrationfrom
aalquwayfili:fix-geodistance-integer-overflow

Conversation

@aalquwayfili

@aalquwayfili aalquwayfili commented Oct 8, 2026 •

Copy link
Copy Markdown

GeoDistanceFeatures gives wrong distances when the coordinates are small int dtypes:

  • Euclidean and manhattan distances overflow in the subtraction. For example uint8 points (1, 2) and (0, 1) give about 40,029 km instead of 157 km.
  • Haversine, the default method, computes in float16 with int8 and uint8 coordinates, and in float32 with int16, so it returns a Float16 or Float32 column and loses precision. For example, New York to Los Angeles gives 3,920.0 km instead of 3,923.6 km with int8 coordinates.
  • The range checks miss the minimum value of signed integer dtypes, because np.abs overflows there. For example, an int8 latitude of -128 passes.

Now transform converts the coordinates to float64 once, so all three methods compute and return float64, and the range checks compare against both bounds instead of using np.abs. Results on float64 coordinates don't change.

Added tests on pandas and polars for the overflow, for integer coordinates giving the same distances as float coordinates with every method, and for the range checks at the integer minimum.

@solegalli

Copy link
Copy Markdown
Collaborator

Hi @aalquwayfili thanks for the contribution and apologies for the delayed response. The bug seems real, the impact seems small but I don't see no reason to fix it.

Could you please target the changes to the narwhals-migration branch? thank you!

@aalquwayfili
aalquwayfili changed the base branch from main to narwhals-migration November 29, 2026 08:50
@aalquwayfili
aalquwayfili force-pushed the fix-geodistance-integer-overflow branch from 0d3786b to 0300171 Compare November 29, 2026 08:50
@aalquwayfili

Copy link
Copy Markdown
Author

Thanks! Moved it to narwhals-migration. The overflow is still there on both pandas and polars, so I made the test run on both.

Converting the coordinates to float64 in transform fixes the overflow for
all methods, and haversine no longer computes in float16 or float32 with
small integer dtypes. The range checks compare against both bounds, since
np.abs overflows on the minimum of signed integer dtypes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@solegalli
solegalli merged commit 10dc8f4 into feature-engine:narwhals-migration Nov 29, 2026
3 of 9 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants