RonakkGovani opened a new pull request, #60249:
URL: https://github.com/apache/spark/pull/60249

   ### What changes were proposed in this pull request?
   
   Change how pandas API on Spark computes Python-style modulo for numeric `%`, 
`rmod` and `np.mod` / `np.remainder`.
   
   Python and NumPy give the result the sign of the divisor, while Spark's 
remainder takes the sign of the dividend. pandas-on-Spark bridged the two with 
`((a % b) + b) % b`. This PR instead adds the divisor to Spark's remainder only 
when their signs differ, which is what NumPy does. A zero result keeps the sign 
of the divisor, as before and as in NumPy.
   
   ### Why are the changes needed?
   
   `((a % b) + b) % b` gives wrong results:
   
   - For an infinite divisor, `a + inf` is `inf` and `inf % inf` is NaN, so 
`np.mod(1.0, inf)` returns NaN instead of `1.0`.
   - A small remainder next to a large divisor is lost: `1e-20 % 1e20` returns 
`0.0` instead of `1e-20`.
   - For integers, the intermediate `(a % b) + b` can overflow. `ps.Series([1]) 
% (2**63 - 1)` fails with `ARITHMETIC_OVERFLOW` under ANSI mode and returns 
`-1` instead of `1` otherwise.
   
   ```python
   >>> import numpy as np
   >>> import pyspark.pandas as ps
   >>> np.mod(ps.Series([1.0]), float("inf"))
   0   NaN
   dtype: float64
   ```
   
   ### Does this PR introduce _any_ user-facing change?
   
   Yes. The results now match pandas:
   
   ```python
   >>> np.mod(ps.Series([1.0]), float("inf"))
   0    1.0
   dtype: float64
   ```
   
   ### How was this patch tested?
   
   Added `test_mod_sign_of_divisor` to 
`pyspark.pandas.tests.data_type_ops.test_num_mod`. It covers infinite and 
finite divisors, `%`, `np.mod`, reverse modulo, Series-Series modulo, the sign 
of zero results, small remainders and integral operands near the int64 bounds. 
The new test fails without this change. Also ran `test_num_mod`, 
`test_num_reverse`, `test_num_mul_div`, `test_num_arithmetic` and 
`test_numpy_compat` locally.
   
   ### Was this patch authored or co-authored using generative AI tooling?
   
   Generated-by: Isaac (Claude Opus 5.5)
   
   This pull request and its description were written by Isaac.
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to