3

In my code I started noticing that the same initial conditions would output different results.

After hours of hunting, I found where the bug occurs.

I have a simple function, which takes a few parameters, one of which is v. v is a double. One of the calculations inside that function is Math.pow(v, 2).

After writing some code that recorded all the inputs of that function and all the intermediate calculations inside that function, I've discovered that v is always equal -54.35178459279, but sometimes

Math.pow(-54.35178459279, 2) = 2954.116488421044

and sometimes (look at the ending 3)

Math.pow(-54.35178459279, 2) = 2954.1164884210443

What? What's going on?


I've tried running Math.pow(-54.35178459279, 2) in an infinite loop to see if it sometimes gives a different output. Well, it doesn't.

My only guesses so far is that either:

a. My debugger does not show all the digits in a number

b. That even though the debugger shows the same representation for vs, the underlying scala double is slightly different.


For those who really want an example, this is really the best I can do:

val precision = 1000000000000.0
def step(v: Double) = {
  val newV = Math.round(calcV(v)*precision) / precision
  step(newV)
}

def calcV(v: Double) = Math.pow(v, 2)

Just got a clue:

scala> -54.35178459279 * -54.35178459279
res0: Double = 2954.1164884210443
scala> Math.pow(-54.35178459279, 2)
res0: Double = 2954.116488421044
Anton
  • 2,282
  • 26
  • 43
  • 1
    You may need an [SSCCE](http://sscce.org) for this. – djechlin Nov 18 '15 at 17:41
  • How did you calculate or assign the values of `v` that led to different square values? – rgettman Nov 18 '15 at 17:42
  • Naive debugging guesses: try printing `v` with high precision, or try creating a `Set` of all the different `v` and see how big it is. Or cache the last value of `v` and see if it changes. – djechlin Nov 18 '15 at 17:43
  • 3
    http://stackoverflow.com/questions/26746623/math-pow-yields-different-results-upon-repeated-calls? – Johny T Koshy Nov 18 '15 at 17:44
  • @djechlin Actually, I do cache the numbers. The two `v`s are identical in the cache (`cache(0) == cache(1) = true`) – Anton Nov 18 '15 at 17:51
  • @johny looks right. Closing as dupe, reopen if you find evidence o/w. – djechlin Nov 18 '15 at 18:46
  • No, it's not. I downloaded java 8u66, and I still get the same error. It's the version on this page http://bugs.java.com/bugdatabase/view_bug.do?bug_id=8063086. – Anton Nov 18 '15 at 18:51

0 Answers0