List.iterate[Double]

Previous Topic Next Topic
 
classic Classic list List threaded Threaded
3 messages Options
Reply | Threaded
Open this post in threaded view
|

List.iterate[Double]

Jan Paw
Hi,

I'm found some strange behavior forscala.collection.generic.GenTraversableFactory#iterate[Double]

scala> List.iterate(0.0, 10)(_ + 0.1)
res0: List[Double] = List(0.0, 0.1, 0.2, 0.30000000000000004, 0.4, 0.5, 0.6, 0.7, 0.7999999999999999, 0.8999999999999999)


This is coused by the JVM (1.8x64) or Scala(2.11.4)?

Cheers,
Jan Paw

--
You received this message because you are subscribed to the Google Groups "scala-internals" group.
To unsubscribe from this group and stop receiving emails from it, send an email to [hidden email].
For more options, visit https://groups.google.com/d/optout.
Reply | Threaded
Open this post in threaded view
|

Re: List.iterate[Double]

Rex Kerr-2
This is caused by Double being a binary fraction approximation to decimals.  It's true on your computer's hardware (so also true on Java, Scala, C, etc.).  If you dislike this behavior, you can use BigDecimal (it is much slower, but often one doesn't care).

  --Rex

On Thu, Nov 27, 2014 at 11:55 AM, Jan Paw <[hidden email]> wrote:
Hi,

I'm found some strange behavior forscala.collection.generic.GenTraversableFactory#iterate[Double]

scala> List.iterate(0.0, 10)(_ + 0.1)
res0: List[Double] = List(0.0, 0.1, 0.2, 0.30000000000000004, 0.4, 0.5, 0.6, 0.7, 0.7999999999999999, 0.8999999999999999)


This is coused by the JVM (1.8x64) or Scala(2.11.4)?

Cheers,
Jan Paw

--
You received this message because you are subscribed to the Google Groups "scala-internals" group.
To unsubscribe from this group and stop receiving emails from it, send an email to [hidden email].
For more options, visit https://groups.google.com/d/optout.

--
You received this message because you are subscribed to the Google Groups "scala-internals" group.
To unsubscribe from this group and stop receiving emails from it, send an email to [hidden email].
For more options, visit https://groups.google.com/d/optout.
Reply | Threaded
Open this post in threaded view
|

Re: List.iterate[Double]

Jerzy Muller
Also, 0.1 is infinite recurring fraction when encoded in decimal, which causes rounding here. If you change it to 0.25 it should work as expected.

--
You received this message because you are subscribed to the Google Groups "scala-internals" group.
To unsubscribe from this group and stop receiving emails from it, send an email to [hidden email].
For more options, visit https://groups.google.com/d/optout.