> -----Original Message-----
> From: Kevin Avila [mailto:[EMAIL PROTECTED]]
> Sent: 09 January 2003 04:33
> 
>       I'm having a weird issue with float precision. I am 
> decrementing the 
> value of a float by 0.1. The problem is when the float I am working 
> with reaches 0.1 and I decrement it again I get 1.e09 instead of the 
> expected 0.0. This was also confirmed by a user in #php. Anyone have 
> any ideas?

Since, mathematically, the binary representations of floats used on computers in 
general is only an approximation to the real value (albeit a very close 
approximation), you can never rely on repeated subtraction of one float from another 
value to end up exactly where you thought it would.  When I were a lad, learning about 
these new-fangled computer thingies at university, it was drummed into us never to do 
this:

   for ($x=0; $x<10.0; $x+=0.1) { ... stuff involving $x ... }

but either this:

   for ($x=0; abs($x-10.0)<a_very_small_value; $x+=0.1) {... stuff ...}

or, better yet:

   for ($i=0; $i<100; $i++) { $x=$i*0.1; .... stuff .... }

The first version tests for an end value that's *close enough* to the desired one, but 
errors in the approximation of 0.1 will still get magnified along the way.  The second 
version is better because you're dealing with exact integer quantities, and 
calculating the closest representation of the desired float each time round the loop 
-- no magnification of approximation errors, and a well-defined termination condition.

(Well, actually, since C hadn't been invented yet (nor even B, and no that's not a 
joke!), the syntax we used was a lot uglier than that, but the principle's the same! ;)

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