如何在PHP中模拟单精度浮点操作? [英] How to emulate single precision float operations in PHP?

查看:216
本文介绍了如何在PHP中模拟单精度浮点操作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将一个简单的C程序移植到PHP。目前我们必须开始这个过程并解析它的输出。该程序是非常微不足道的,但是对于算法使用 float 是非常重要的,因为这些错误总结起来并且结果将会消失。



例如:

  #include< stdio.h> 

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

返回0;



$ b

PHP示例:



$ b pre> <?php

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

?>

C示例将会导致 122868.343750 122868.349440 ,而PHP最终会以 122868.349440



如何在PHP中获得C float 结果?

解决方案

是不是你可以做到这一点使用内置的PHP函数。

使用double的那个给你真实的结果,100%精确。浮动的一个是错误的。

在PHP中,float和double是相同的类型,也就是double。



如果你需要高精度的结果,总是给出相同的结果,请尝试使用BC数学模块: http://php.net/bcmath



使用BC Math的示例代码:

  $ result = bcmul(123456,0.99524,6); //给出122868.34944 
$ result = number_format($ result,6,。,); // 122868.349440 - 追加零
echo $ result;

输出:

  122868.349440 

如果您确实需要与C程序相同的结果,那么你有2个选项:
$ b $ ol

  • 通过编写一个php扩展来创建你自己的类似于c的函数: http://www.google.com/search?q=writing+php+extensions 通过函数proc_open()从PHP中与您的C程序对话:
    http://www.php.net/manual/en/function.proc-open.php (另请参阅popen(),exec ()或shell_exec())



  • 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?

    解决方案

    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())

    这篇关于如何在PHP中模拟单精度浮点操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆