0

I am trying to generate a Numeric Range of Double by val arrayOfDoubles = (0.0 to 1.0 by 0.1).toArray, but the resultant is not what I expected it to be. the result is something like Array(0.0, 0.1, 0.2, 0.30000000000000004, 0.4, 0.5, 0.6, 0.7, 0.7999999999999999, 0.8999999999999999, 0.9999999999999999). Why is it like this. I could use this code to get what I expect it to be:

val roundedArray = for (x <- arrayOfDoubles) yield  BigDecimal(x).setScale(1, BigDecimal.RoundingMode.HALF_UP).toDouble

Which results in Array[Double] = Array(0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0)But this looks really cumbersome and expensive for BigDecimal converts the double to String and then parse it.

Is there a way I could get the NumericRange already rounded to one decimal place?

Thanks.

atalpha
  • 320
  • 1
  • 7
  • 19

2 Answers2

3
0 to 10 map (_ / 10.0)

should do the trick

Gavin
  • 6,180
  • 3
  • 25
  • 25
  • Thanks for the reply. Can you please edit it to `0 to 10 map (_.toDouble / 10)` because your code produces Vector(0, 0, 0, 0, 0, 0, 0, 0, 0, 1), so I could accept it as an answer. I tried to edit this answer, but for some strange reason it was rejected. – atalpha Mar 28 '17 at 14:55
  • 2
    Note the division is by 10.0 which results in double scala.collection.immutable.IndexedSeq[Double] = Vector(0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0) – Gavin Mar 28 '17 at 14:59
0

Floating point arithmetic is not exact, i.e. some decimal numbers cannot be represented exactly, and are represented by the closest available numbers. See also Is floating point math broken?

Community
  • 1
  • 1
radumanolescu
  • 4,059
  • 2
  • 31
  • 44