> -----Original Message-----
> From: James E Hicks III [mailto:[EMAIL PROTECTED]
> Sent: 14 March 2003 18:22
> 
> Help save my sanity! What can I do to the IF statement in the 
> following code to
> make it print the line that says "By God they are equal in 
> value."? I have tried
> the following changes;
> 
>       1. using === instead of ==
>       2. placing (float) in front of the $i and $target 
> inside and before the IF
> statement.
> 
> <?
> $start = 215;
> $end = 217;
> $target = 216;
> for ($i=$start; $i<=$end; $i+=.1){
>         if ( $i ==  $target ){
>                 echo ("<BR>$i - $target, By God, the are 
> equal in value.");
>         } else {
>                 echo ("<BR>$i - $target, Eternal Damnation, 
> they aren't
> equal!");
>         }
> }
> ?>

Rule 1: DON'T USE FLOATS AS LOOP CONTROL VARIABLES.

Rule 2: DON'T COMPAR|E CALCULATED FLOATING POINT VALUES FOR EQUALITY.

By the vary nature of how floating-point numbers are stored on computers,
there is a tiny inaccuracy in all floating point operations.  In many cases
this dosn't matter -- the inaccuracy is beyond the level of significance.
However, if you compare two calculated values to each other, you must always
allow for the possiblity of that tiny inaccuracy -- for example, don't do:

   if ((10.0/3.0)*3.0 == 10.0)  // *never* true!

but instead something like:

   if (abs((10.0/3.0)*3.0 - 10.0) < 1e-30) // adjust 1e-30 to suit 

In loops like the one you've written, you compound the inaccuracy by doing
many floating-point additions to the same variable -- by the time you reach
your endpoint, you're probably significantly off.  The only way to truly
compensate for this is to use integers to control your loop, and divide down
by the appropriate power of 10 at the start of each iteration, so:

   $start = 215;
   $end = 217;
   $target = 216;
   for ($ii=$start*10; $ii<=$end*10; $ii++){
      $i = $ii/10.0;

      // etc.

   }

Cheers!

Mike

---------------------------------------------------------------------
Mike Ford,  Electronic Information Services Adviser,
Learning Support Services, Learning & Information Services,
JG125, James Graham Building, Leeds Metropolitan University,
Beckett Park, LEEDS,  LS6 3QS,  United Kingdom
Email: [EMAIL PROTECTED]
Tel: +44 113 283 2600 extn 4730      Fax:  +44 113 283 3211 

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php

Reply via email to