0

Here is the php code: when $lat and $lng equal to 0.087 after the increment, the while loop returns false and break the loop when it should return true because it is a <= operator. Can someone explains to me why?

$lat = 0.029;
$lng = 0.029; 
while ( $lat <= 0.087 && $lng <= 0.087 ){
   $lat += 0.029;
   $lng += 0.029;
}
  • See the warning on this page: http://www.php.net/manual/en/language.types.float.php and more particularly the note about base 10 to base 2 conversion. – Arnauld Jul 06 '14 at 23:14
  • I think that you need to read about comparison floats: http://stackoverflow.com/q/3148937/1503018 – sectus Jul 07 '14 at 01:29

2 Answers2

0

Looks like you're having a problem with floating point notation as they discuss here:
PHP rounding error
What to do about it is another question... you can use the bcadd function like this:

$lat = 0.029;
$lng = 0.029;
$c = 0.029;

while ( $lat <= 0.087 && $lng <= 0.087){

   $lat = bcadd($lat, $c, 3);
   $lng = bcadd($lng, $c, 3);

}
Community
  • 1
  • 1
Joe T
  • 2,300
  • 1
  • 19
  • 31
  • Thanks Alot for the explanation. The provided method worked as well. I wish I can upvote you if I have points to do so. – user3053729 Jul 07 '14 at 04:48
0

Check if you have BC Math or GMP.

<?php

if (class_exists("GMP")) {
  $lat = new GMP(0.029);
  $lng = new GMP(0.029);
  while ($lat <= 0.087 && $lng <= 0.087) {
    $lat += 0.029;
    $lng += 0.029;
  }
}
elseif (function_exists("bcadd")) {
  $lat = 0.029;
  $lng = 0.029;
  while ($lat <= 0.087 && $lng <= 0.087) {
    $lat = bcadd($lat, 0.029, 3);
    $lng = bcadd($lng, 0.029, 3);
  }
}
else {
  trigger_error("Please install GMP of BC Math.");
}
Fleshgrinder
  • 15,703
  • 4
  • 47
  • 56
  • if you use bcadd() without a scale, those decimals < 1 turn into 0 and you're stuck in an infinite loop – Joe T Jul 06 '14 at 23:44