hanover-fiste commented on a change in pull request #31965:
URL: https://github.com/apache/spark/pull/31965#discussion_r602129852



##########
File path: 
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/jdbc/JDBCRelation.scala
##########
@@ -118,13 +119,28 @@ private[sql] object JDBCRelation extends Logging {
           s"Upper bound: ${boundValueToString(upperBound)}.")
         upperBound - lowerBound
       }
-    // Overflow and silliness can happen if you subtract then divide.
-    // Here we get a little roundoff, but that's (hopefully) OK.
-    val stride: Long = upperBound / numPartitions - lowerBound / numPartitions
+
+    // Overflow can happen if you subtract then divide. For example:
+    // (Long.MaxValue - Long.MinValue) / (numPartitions - 2).
+    // Also, using fixed-point decimals here to avoid possible inaccuracy from 
floating point.
+    val strideUpperCalculation = (upperBound / BigDecimal(numPartitions))
+      .setScale(18, RoundingMode.HALF_EVEN)
+    val strideLowerCalculation = (lowerBound / BigDecimal(numPartitions))
+      .setScale(18, RoundingMode.HALF_EVEN)

Review comment:
       I'm using setScale here to handle an issue that can arise with repeating 
decimals. For instance, if you end up with upperStride = 1.333... and 
lowerStride of  0.333..., when doing upperStride - lowerStride, you'd get 
0.999.... This would then be truncated to 0 when converted to a long for 
stride, which is an issue. Using setScale, the repeating decimals are rounded 
and after the subtraction you end up with 1.0. 
   
   The reason I'm using `RoundingMode.HALF_EVEN` is because that's the default 
for BigDecimal. As for a scale of 18, this was a number I picked from prior 
defaults I've encountered (e.g. when a DecimalType is deserialized into 
BigDecimal, the BigDecimal is instantiated as 38,18). However, I could lower 
the scale if you think it is worthwhile. Since these calculations are at such a 
small scale, I wasn't concerned about BigDecimal performance, but instead 
accuracy. 




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

For queries about this service, please contact Infrastructure at:
us...@infra.apache.org



---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscr...@spark.apache.org
For additional commands, e-mail: reviews-h...@spark.apache.org

Reply via email to