Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to emulate single precision float operations in PHP?

I need to port a simple C program to PHP. Currently we have to start the process and parse it's output. The program is very trivial but it is important for the algorithm to use float as the errors will sum up and the result will be way off.

C example:

#include <stdio.h>

int main( void ) {
  printf("%f\n", 123456 * (float)0.99524);
  printf("%f\n", 123456 * (double)0.99524);

  return 0;
}

PHP example:

<?php

printf("%f\n", 123456 * 0.99524);

?>

The C example will result in 122868.343750 and 122868.349440 while PHP will end up with 122868.349440.

How do I get the C float result in PHP?

like image 990
Miko Avatar asked Nov 13 '22 14:11

Miko


1 Answers

There is no way you can do this using built in php functions.

The one using "double" gives you the real result, 100% precise. The float one is wrong.

In PHP float and double are the same type, which is double.

If you need high precision results, that always give the same results, try using BC Math module: http://php.net/bcmath

Example code using BC Math:

$result = bcmul("123456", "0.99524", 6); // gives 122868.34944
$result = number_format($result, 6, ".", ""); // 122868.349440 - appending zeros
echo $result;

Output:

122868.349440

If you really, really want the same result as in the C program, then you have 2 options:

  1. Create your own c-like function by writing a php extension: http://www.google.com/search?q=writing+php+extensions

  2. Talk to your C-program from PHP via function proc_open(): http://www.php.net/manual/en/function.proc-open.php (see also popen(), exec() or shell_exec())

like image 167
Czarek Tomczak Avatar answered Dec 19 '22 08:12

Czarek Tomczak