Tutorial :Imprecise numbers with microtime and floating point addition in PHP



Question:

I'm having a terrible time convincing myself what I've done here is a good idea. The specific section I find objectionable is:

return ((float)($now+$sec).'.'.$mic);  

In order to preserve the floating point precision, I'm forced to either fall back on the BC or GMP libraries (neither of which is always available). In this case, I've resorted to jamming the numbers together with string concatenation.

<?php    // return the current time, with microseconds  function tick() {      list($sec, $mic, $now) = sscanf(microtime(), "%d.%d %d");      return ((float)($now+$sec).'.'.$mic);  }    // compare the two given times and return the difference  function elapsed($start, $end) {      $diff = $end-$start;        // the difference was negligible      if($diff < 0.0001)          return 0.0;        return $diff;  }    // get our start time  $start = tick();    // sleep for 2 seconds (should be ever slightly more than '2' when measured)  sleep(2);    // get our end time  $end = tick();    $elapsed = elapsed($start, $end);    // should produce output similar to: float(2.00113797188)  var_dump($elapsed);    ?>  

If I attempt to add two numbers like 123456789 (representing a timestamp) and 0.0987654321 (representing microseconds), using the addition operator (+) I invariably end up with 123456789.099. Even when casting the integer to float, the result is the same.

Is there a solution for this issue which is 1) not a hack and 2) doesn't involve string concatenation? I shouldn't have to fall back on this sort of garbled code in order to get an accurate timestamp with microsecond resolution.

Edit: As S. Gehrig has explained, floating point numbers in PHP can be, at times, a bit tricky to display. The "precision" indicated in the PHP configuration is regarding display. The actual values are not rounded like I thought. A far simpler solution to the above code would look like so:

// return the current time, with microseconds  function tick() {      return microtime(true);  }    // compare the two given times and return the difference  function elapsed($start, $end) {      return $end-$start;  }    // get our start time  $start = tick();    // sleep for 2 seconds (should be ever slightly more than '2' when measured)  sleep(2);    // get our end time  $end = tick();    $elapsed = elapsed($start, $end);    // should produce output similar to: float(2.00113797188)  var_dump($elapsed);  

If you were to examine $start or $end before subtracting one from the other, it might appear they were rounded to the hundredths position. This is not the case. It seems arbitrary precision is maintained for arithmetic while the display is limited.


Solution:1

Why don't you use microtime(true) which simply returns a microsecond timestamp as float? The parameter [bool] $get_as_float was added in PHP 5.0.0.

Regarding the comment about the "loss" of precision:

$start = microtime(true);  $end = microtime(true);  echo $end - $start;  // prints 7.1526861190796  

microtime(true) is not limited to 2 decimal places. What the poster encounters is the effect of the configuration setting precision which controls how many decimal places will be printed when outputting float variables. This has nothing to do with the internal precision microtime(true) uses. You can always use number_format() or (s)printf() to format the output to the precision you like.


Solution:2

First, spligak, I see that your code contains an error.

list($sec, $mic, $now) = sscanf(microtime(), "%d.%d %d");  return ((float)($now+$sec).'.'.$mic);  

If $mic has fewer than six digits, you get garbage results. Do a desk check on

the case where microtime() returns "0.000009 1234567890"  

Second, you can greatly reduce the floating-point error as follows: (WARNING: untested code!)

// compare the two given times and return the difference

// get our start time  $start = microtime();    // sleep for 2 seconds (should be ever slightly more than '2' when measured)  sleep(2);    // get our end time  $end = microtime();    // work around limited precision math  // subtract whole numbers from whole numbers and fractions from fractions    list($start_usec, $start_sec) = explode(" ", $start);  list($end_usec, $end_sec) = explode(" ", $end);  $elapsed = ((float)$end_usec)-((float)$start_usec);  $elapsed += ((float)$end_sec)-((float)$start_sec);    // please check the output  var_dump($elapsed);  


Solution:3

Floating point types are inherently imprecise. Either live with it, or don't use them.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »