如何解决这个问题在PHP中

如何解决这个问题在PHP中

本文介绍了如何解决这个问题在PHP中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  $ onethird = 1.0 / 3; 
$ fivethirds = 1.0 / 3 + 1.0 / 3 + 1.0 / 3 + 1.0 / 3 + 1.0 / 3;
$ half = 1.0 / 2;
$ threehalf = 1.0 / 2 + 1.0 / 2 + 1.0 / 2;
var_dump($ onethird + $ fivethirds == $ half + $ threehalf);

输出 false ,但正如我们所有知道: 5/3 + 1/3 = 2 = 3/2 + 1/2

这个问题?

解决方案

这是IEEE 754表示浮点数的问题之一。表示不够精确,不足以表示所有有理数。



要做到这一点的方法是将差异与一个非常小的数字进行比较, / $>

  abs(($ onethird + $ fivethirds) - ($ half + $ threehalf))< 1e-8 


$onethird = 1.0/3;
$fivethirds = 1.0/3+1.0/3+1.0/3+1.0/3+1.0/3;
$half = 1.0/2;
$threehalf = 1.0/2+1.0/2+1.0/2;
var_dump($onethird + $fivethirds == $half + $threehalf);

which outputs false,but as we all know:5/3+1/3=2=3/2+1/2

How to fix this problem?

解决方案

This is one of the problems with the IEEE 754 representation of floating point numbers; the representations are not accurate enough to represent all rational numbers.

The way to do it is to compare the difference against a very small number for closeness, rather than equality:

abs(($onethird + $fivethirds) - ($half + $threehalf)) < 1e-8

这篇关于如何解决这个问题在PHP中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-07 08:48