andygrove opened a new issue, #12426: URL: https://github.com/apache/arrow-rs/issues/12426
### Describe the bug `arrow_arith::numeric::div` on decimals truncates the quotient toward zero at the result scale. The result scale follows the MySQL/PostgreSQL convention of adding 4 to the dividend's scale (the comment in `decimal_op` says "Follow postgres and MySQL adding a fixed scale increment of 4"). The change that introduced these semantics was described as making decimal division "match that of postgres, mysql and Hive" ([apache/datafusion#6832 review comment](https://github.com/apache/datafusion/pull/6832#discussion_r1278622708)). All three of those systems round the quotient. None of them truncate it. So the last digit of a quotient is often one unit too small in magnitude. For example, 2 / 3 is `0.666666` where MySQL, at the same scale 6, gives `0.666667`. The truncation is in the digit-at-a-time division helper, whose doc comment says it "truncates toward zero": https://github.com/apache/arrow-rs/blob/6a3f719f1de43137f0ecc2e7de12d4a7a0b13bd5/arrow-arith/src/numeric.rs#L1432 ### To Reproduce Through DataFusion (`datafusion-cli` 55.3.0), whose `/` on decimals calls this kernel: ```sql select cast(2 as decimal(10,2)) / cast(3 as decimal(10,2)); -- 0.666666 (Decimal128(16, 6)) select cast(-2 as decimal(10,2)) / cast(3 as decimal(10,2)); -- -0.666666 select cast(2 as decimal(38,2)) / cast(3 as decimal(38,2)); -- 0.666666 (Decimal128(38, 6)) ``` The same expressions elsewhere: | | 2 / 3 | -2 / 3 | |---|---|---| | arrow-rs (via DataFusion 55.3.0) | `0.666666` | `-0.666666` | | MySQL 8.4.13 (same result scale, 6) | `0.666667` | `-0.666667` | | PostgreSQL 16 | `0.66666666666666666667` | `-0.66666666666666666667` | ### Expected behavior The quotient is rounded to the result scale, half away from zero, as MySQL and PostgreSQL do. For example, `0.666667` and `-0.666667` above. ### Additional context The truncation compounds in expressions that divide more than once, and in ratios of sums. For example, TPC-DS Q58's `x / ((x + y + z) / 3) * 100` loses the last digit before the multiplication scales the error up. The decimal `AVG` in DataFusion has the same issue independently (it divides the sum by the count with integer division). I'll report it there. -- 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]
