RE: [PHP] Stuck... Long day I think.. ;-)

From: Date: Mon, 19 May 2003 15:07:32 +0000
Subject: RE: [PHP] Stuck... Long day I think.. ;-)
Groups: php.general 
Request: Send a blank email to php-general+get-148171@lists.php.net to get a copy of this message
> -----Original Message----- > From: Brian V Bonini [mailto:b-bonini@cox.net] > Sent: 17 May 2003 00:44 > To: Frappy John > Cc: PHP Lists > Subject: Re: [PHP] Stuck... Long day I think.. ;-) > > > On Fri, 2003-05-16 at 19:19, Frappy John wrote: > > > I do the same thing here and it works fine: > > > > > > for($i = 250; $i <= 1000; $i += 250) { > > > $c_val[] = $i; > > > } > > . . . > > > I'm not seeing the difference in terms of functionality. > > > > One big difference is your protein routine deals with > > decimals (floating point) and your calories routine deals > > with whole numbers (integers). > > > > One general rule of thumb is never to test a floating point > > number for equality. > > Ah, I did not know that, thanks. So any suggestions for how > to approach > this then? I guess I need to convert those values to > something else and > test them?? Well, there's 2 ways to approach this: either scale your numbers up so you can hold them as integers, dividing by an appropriate power of 10 when the need arises, or build an appropriate margin of error (or "delta") into your comparisons. Of these, only the integer representation method is really safe with loops, as otherwise the inherent (althoug minute) errors in the computer representations of float values can build up sufficiently that the error will eventually exceed even a reasonable delta value. Taking the integer representation approach, your loop might be written as: for($i = 10; $i <= 20; ++$i) { $float_i = $i/10.0; ... } If you have no loop-control variables involved, a test involving a delta margin-of-error value might go like this: $ten = 10.0 / 3.0 * 3.0; // almost never exactly 10.0, on // any computer architecture! $delta = 1e-15; // some suitably small value if (abs($ten-10.0)<$delta): echo "Good: within the margin of error"; else: echo "Bad: not close enough!" endif; 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: m.ford@lmu.ac.uk Tel: +44 113 283 2600 extn 4730 Fax: +44 113 283 3211

« previous php.general (#148171) next »