Jason Zhu Jason Zhu - 18 days ago 5
Scala Question

scala range precision for float step

I intend to generate an array from 0.05 to 0.95 with step 0.05, just like

0.05, 0.1, 0.15, 0.2, ...
. But the following code has some precision problems:

scala> 0.05 to 0.95 by 0.05
res11: scala.collection.immutable.NumericRange[Double] = NumericRange(0.05, 0.1, 0.15000000000000002, 0.2, 0.25, 0.3, 0.35, 0.39999999999999997, 0.44999999999999996, 0.49999999999999994, 0.5499999999999999, 0.6, 0.65, 0.7000000000000001, 0.7500000000000001, 0.8000000000000002, 0.8500000000000002, 0.9000000000000002)


Could anyone give me some idea on how to solve this problem? Thanks.

Answer

If you need precise decimal calculations, the actually reliable way is to use BigDecimal:

BigDecimal("0.05") to BigDecimal("0.95") by BigDecimal("0.05")

It's a lot slower, so not acceptable in some contexts, but that's the reality of working with decimals on modern computers.

Comments