Copilot commented on code in PR #55338:
URL: https://github.com/apache/arrow/pull/55338#discussion_r4569728975


##########
r/R/expression.R:
##########
@@ -216,6 +216,41 @@ Expression$op <- function(FUN, ..., args = list(...)) {
     }
     return(out)
   } else if (FUN == "%%") {
+    # Prefer `modulo` for exact types over rewriting through `%/%`, which goes
+    # via float64 and loses int64/decimal precision.
+    exact_type_ids <- .exact_arithmetic_type_ids()
+    is_exact <- function(x) {
+      is.integer(x) ||
+        (inherits(x, "ArrowObject") && x$type_id() %in% exact_type_ids)
+    }
+
+    if (is_exact(args[[1]]) && is_exact(args[[2]])) {
+      if (inherits(args[[1]], "ArrowObject")) {
+        out_type <- args[[1]]$type()
+      } else {
+        out_type <- int32()
+      }
+      if (inherits(args[[2]], "ArrowObject")) {
+        divisor_type <- args[[2]]$type()
+      } else {
+        divisor_type <- int32()
+      }
+      # `modulo` errors on divide-by-zero; R returns NA for integer `%% 0`.
+      zero <- Expression$op("==", args[[2]], 0L)

Review Comment:
   Comparing a `decimal128(38, 30)` divisor with int32 `0L` requires promotion 
to the invalid type `decimal128(40, 30)`, so the zero check fails even when 
modulo supports both original operands. Construct the comparison zero directly 
with `divisor_type`, rather than comparing against an int32 scalar. Apply the 
same change to the eager zero check in `r/R/arrow-datum.R:214`.



##########
r/tests/testthat/test-dplyr-funcs-math.R:
##########
@@ -464,6 +464,52 @@ test_that("floor division maintains type consistency with 
R", {
   )
 })
 
+test_that("%% uses the modulo kernel for large int64 and decimals", {
+  skip_if_not_installed("bit64")
+
+  # 2^60 + 5 needs 61 bits, so the old %% rewrite, which divided through
+  # float64, could not return its exact remainder. 2^60 = (2^3)^20 = 1 mod 7,
+  # so the exact remainder is 6.
+  big <- Array$create(bit64::as.integer64("1152921504606846981"))
+  expect_equal(as.double(as.vector(big %% 7L)), 6)
+  expect_equal((big %% 7L)$type, int64())
+  # R rounds towards negative infinity for %%, which the kernel also does.
+  negative <- Array$create(bit64::as.integer64("-7"))
+  expect_equal(as.double(as.vector(negative %% 3L)), 2)
+
+  # Decimal with many significant digits: the old rewrite was silently wrong.
+  d <- Scalar$create("12345678901234567890.12", string())$cast(decimal128(25, 
2))
+  expect_equal(as.vector(d %% 7L), 1.12)
+})
+
+test_that("integer %% 0 returns NA like base R", {
+  expect_true(is.na(as.vector(Array$create(5L) %% 0L)))
+  expect_equal(
+    as.vector(Array$create(c(5L, 0L, NA_integer_)) %% 0L),
+    as.vector(c(5L, 0L, NA_integer_) %% 0L)
+  )
+})
+
+test_that("dplyr %% matches base R for int64 and zero divisor", {
+  skip_if_not_installed("bit64")

Review Comment:
   All `mod_big` remainders fit in int32, so `collect()` downcasts them to 
ordinary R integers by default, while bit64's reference result retains its 
`integer64` class. This makes `compare_dplyr_binding()` fail on types despite 
correct remainders. Disable `arrow.int64_downcast` locally for this test.



##########
r/R/arrow-datum.R:
##########
@@ -201,8 +201,34 @@ eval_array_expression <- function(FUN, ..., args = 
list(...), options = empty_na
       return(eval_array_expression("floor", out))
     }
   } else if (FUN == "%%") {
+    # Use Arrow's floored `modulo` kernel (R `%%` / Python `%` semantics) for
+    # exact types so int64 and decimal keep their native precision. The rewrite
+    # below casts both sides through float64, which loses that precision.
+    exact_type_ids <- .exact_arithmetic_type_ids()
+    numerator_is_exact <- args[[1]]$type_id() %in% exact_type_ids
+    denominator_is_exact <- args[[2]]$type_id() %in% exact_type_ids
+
+    if (numerator_is_exact && denominator_is_exact) {
+      # `modulo` errors on divide-by-zero; R returns NA for integer `%% 0`.
+      # Replace zero divisors before calling the kernel, then restore NA.
+      zero <- eval_array_expression("equal", args[[2]], 0L)
+      safe_divisor <- eval_array_expression(
+        "if_else",
+        zero,
+        Scalar$create(1L)$cast(args[[2]]$type),
+        args[[2]]
+      )
+      rem <- call_function("modulo", args = list(args[[1]], safe_divisor))
+      return(eval_array_expression(
+        "if_else",
+        zero,
+        Scalar$create(NA_integer_)$cast(args[[1]]$type),

Review Comment:
   The int32 casts here and at line 225 require decimal precision of at least 
`10 + scale`, regardless of the scalar value, so valid `decimal128(5, 2)` 
operands now fail. Replace both placeholders with null-typed scalars cast to 
the target types; `modulo` skips null divisors and preserves the required NA 
result.



##########
r/R/expression.R:
##########
@@ -216,6 +216,41 @@ Expression$op <- function(FUN, ..., args = list(...)) {
     }
     return(out)
   } else if (FUN == "%%") {
+    # Prefer `modulo` for exact types over rewriting through `%/%`, which goes
+    # via float64 and loses int64/decimal precision.
+    exact_type_ids <- .exact_arithmetic_type_ids()
+    is_exact <- function(x) {
+      is.integer(x) ||
+        (inherits(x, "ArrowObject") && x$type_id() %in% exact_type_ids)
+    }
+
+    if (is_exact(args[[1]]) && is_exact(args[[2]])) {
+      if (inherits(args[[1]], "ArrowObject")) {
+        out_type <- args[[1]]$type()
+      } else {
+        out_type <- int32()
+      }
+      if (inherits(args[[2]], "ArrowObject")) {
+        divisor_type <- args[[2]]$type()
+      } else {
+        divisor_type <- int32()
+      }
+      # `modulo` errors on divide-by-zero; R returns NA for integer `%% 0`.
+      zero <- Expression$op("==", args[[2]], 0L)
+      safe_divisor <- Expression$create(
+        "if_else",
+        zero,
+        Scalar$create(1L, divisor_type),

Review Comment:
   A valid decimal divisor type need not be able to represent 1. For example, 
`decimal128(2, 2)` supports 0.25 but cannot hold 1.00, so constructing this 
scalar makes a dplyr query computing 0.75 %% 0.25 fail even though the divisor 
is nonzero. Replace zero divisors with a typed null instead; the modulo kernel 
propagates nulls without dividing by zero.



-- 
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]

Reply via email to