svn: /phpdoc/en/trunk/language/types/ float.xml

From: Date: Tue, 31 Jan 2012 19:36:00 +0000
Subject: svn: /phpdoc/en/trunk/language/types/ float.xml
Groups: php.doc.cvs 
Request: Send a blank email to doc-cvs+get-9531@lists.php.net to get a copy of this message
frozenfire Tue, 31 Jan 2012 19:36:00 +0000 Revision: http://svn.php.net/viewvc?view=revision&revision=322982 Log: Described normative means of testing floating point numbers for equality using a machine epsilon. Changed paths: U phpdoc/en/trunk/language/types/float.xml Modified: phpdoc/en/trunk/language/types/float.xml =================================================================== --- phpdoc/en/trunk/language/types/float.xml 2012-01-31 18:26:22 UTC (rev 322981) +++ phpdoc/en/trunk/language/types/float.xml 2012-01-31 19:36:00 UTC (rev 322982) @@ -66,10 +66,10 @@ </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 @@ </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>

« previous php.doc.cvs (#9531) next »