0

So I've been doing some math trying to use this loop for my project and I cannot understand no matter how hard I try why does this loop run two times instead of one.

$currValue = 40.3;
$maxValue = 40.6;

while ($currValue < $maxValue) {
  $maxValue = $maxValue - 0.3;
  echo $maxValue . '<br>';
}

// Output:
// 40.3
// 40.0

I would be really grateful if somebody provided me with some sort of explanation on this and or a way to work around this. I hope this question isn't a duplicate, I didn't manage to find anything similliar.

Sainthrax
  • 23
  • 6

3 Answers3

1

Run this it should demonstrate what the problems is. Its related to IEEE floating point representations being slightly inaccurate for some numbers.

<?php
$currValue = 40.3;
$maxValue = 40.6;

while ($currValue <= $maxValue) {
  $maxValue = $maxValue - 0.3;
  echo 'maxValue -  ' . number_format($maxValue, 20) . ' currValue = ' . number_format($currValue,20) . '<br>';
}
RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
  • Best to look at something clever that I am https://en.wikipedia.org/wiki/IEEE_floating_point. Its a mine field for sure! – RiggsFolly Aug 04 '15 at 11:22
  • And this http://stackoverflow.com/tags/floating-point/info and this http://stackoverflow.com/questions/588004/is-floating-point-math-broken – RiggsFolly Aug 04 '15 at 11:29
0
 $currValue = 40.3;
 $maxValue = 40.6;



 while (round( $currValue, 1) < round($maxValue,1)) {

  $maxValue = $maxValue - 0.3;
  echo $maxValue . '<br>';
 }
Harish Lalwani
  • 754
  • 5
  • 20
  • Could you explain your answer further? – moopet Aug 04 '15 at 13:19
  • while executing the code in question the loop was executing one more time. This was because of representation floating point numbers. Therefore I have rounded of these numbers before comparing them thereby having a range for precision check while comparing. – Harish Lalwani Aug 04 '15 at 14:05
0

Use rounded value in the loop like

round($maxValue,1)

instead of

$maxValue
sujivasagam
  • 1,659
  • 1
  • 14
  • 26