Described normative means of testing floating point numbers for equality using a machine epsilon.

git-svn-id: https://svn.php.net/repository/phpdoc/en/trunk@322982 c90b9560-bf6c-de11-be94-00142212c4b1
This commit is contained in:
Justin Martin 2012-01-31 19:36:00 +00:00
parent b98758b484
commit 9592699ed0

View file

@ -66,10 +66,10 @@ EXPONENT_DNUM [+-]?(({LNUM} | {DNUM}) [eE][+-]? {LNUM})
</para>
<para>
So never trust floating number results to the last digit, and never compare
floating point numbers for equality. If higher precision is necessary,
the <link linkend="ref.bc">arbitrary precision math functions</link> and
<link linkend="ref.gmp">gmp</link> functions are available.
So never trust floating number results to the last digit, and do not compare
floating point numbers directly for equality. If higher precision is
necessary, the <link linkend="ref.bc">arbitrary precision math functions</link>
and <link linkend="ref.gmp">gmp</link> functions are available.
</para>
</warning>
@ -88,6 +88,43 @@ EXPONENT_DNUM [+-]?(({LNUM} | {DNUM}) [eE][+-]? {LNUM})
</para>
</sect2>
<sect2 xml:id="language.types.float.comparison">
<title>Comparing floats</title>
<para>
As noted in the warning above, testing floating point values for equality is
problematic, due to the way that they are represented internally. However,
there are ways to make comparisons of floating point values that work around
these limitations.
</para>
<para>
To test floating point values for equality, an upper bound on the relative
error due to rounding is used. This value is known as the machine epsilon,
or unit roundoff, and is the smallest acceptable difference in calculations.
</para>
<informalexample>
<simpara>
<varname>$a</varname> and <varname>$b</varname> are equal to 5 digits of
precision.
</simpara>
<programlisting role="php">
<![CDATA[
<?php
$a = 1.23456789;
$b = 1.23456780;
$epsilon = 0.00001;
if(abs($a-b) < 0.00001) {
echo "true";
}
?>
]]>
</programlisting>
</informalexample>
</sect2>
<sect2 xml:id="language.types.float.nan">
<title>NaN</title>