2

When setting a value for an index using a formula to calculate the index, something like $arr[((40.9+0.00004)*100000)] = 1;, in the expected result my array should have the value for index as so: [4090004]=>1; instead I got [4090003]=>1.

Can someone please give me an insight into what's going on?

I was able to get around this by casting the index to a string $arr[(string) ((40.9+0.0004)*100000)] = 1;, but I would like to understand the underlying mechanics that caused this to happen.

UPDATE

This is not directly connected to this question Is floating point math broken? — while the answer might have to do with that floating point bug, I am trying to understand how it effects me here.

Armali
  • 18,255
  • 14
  • 57
  • 171
Yehuda Schwartz
  • 3,378
  • 3
  • 29
  • 38
  • 1
    (Incidentally, I get `[4090039]=>1` when I try it.) – ceejayoz Oct 22 '18 at 20:05
  • 1
    read the Warning here - http://php.net/manual/en/language.types.float.php – MakeLoveNotWar Oct 22 '18 at 20:07
  • @ceejayoz i just edited the formula now you will see what i'm talking about (was supposed to be .00004) – Yehuda Schwartz Oct 22 '18 at 20:15
  • 1
    Your issue remains the same - this is what happens with floating point math. – ceejayoz Oct 22 '18 at 20:16
  • @ceejayoz this has nothing to do with math if you `echo ((40.9+0.00004)*100000)` the result is 4090004 it has to do with setting my array index with a float – Yehuda Schwartz Oct 22 '18 at 20:25
  • "The results of my floating point math calculation have nothing to do with floating point math" is an... *interesting* assertion. – ceejayoz Oct 22 '18 at 20:29
  • (Here, try this and you'll see what's going on: `echo number_format((float) ((40.9+0.00004)*100000), 20);`. On my computer it comes out to `4,090,003.99999999953433871269`. – ceejayoz Oct 22 '18 at 20:33
  • 1
    i think he is saying the calculation in the array key and not in the array key is different: https://ideone.com/2tlPxj –  Oct 22 '18 at 20:35
  • 2
    @IdontDownVote Chances are internally echoing (and thus casting to string) rounds and the array key truncates. http://php.net/manual/en/language.types.array.php indicates "Floats are also cast to integers, which means that the fractional part will be truncated. E.g. the key 8.7 will actually be stored under 8." – ceejayoz Oct 22 '18 at 20:37
  • 2
    In a nutshell: your number isn't *exactly* 4090004; it will get *rounded* by some operations like casting to a string, and *truncated* (the insignificant bits discarded) by other operations like casting to an integer. – deceze Oct 23 '18 at 07:57

0 Answers0