Page 1 of 1

failing <= inside 'for ()'

Posted: Sun Mar 23, 2003 2:04 pm
by easyTree
Hi :)

I'm relatively new to php but am experienced in other languages; c++, objectPascal etc...

I've got a loop:

Code: Select all

for ($rangeDivisor = 0.85; $rangeDivisor &lt;= 0.95; $rangeDivisor += 0.01) &#123;
  ..
&#125;
which performs as if there were a '<' rather than '<='. ie. the loop contents aren't executed when $rangeDivisor = 0.95.

However, if I multiply all figures by 10 (ie 8.5, 9.5, 0.1) it performs as expected.

What! :) is happening here?

easy - ;)

--
[php 4.3.1 on Win32]

Posted: Sun Mar 23, 2003 2:13 pm
by twigletmac
I see what you mean:

Code: Select all

for ($rangeDivisor = 0.85; $rangeDivisor <= 0.95; $rangeDivisor += 0.01) {
ignores 0.95 but

Code: Select all

for ($rangeDivisor = 0.85; $rangeDivisor < 0.96; $rangeDivisor += 0.01) {
works as you'd expect.

Mac

Posted: Sun Mar 23, 2003 2:23 pm
by Bill H
I suspect it has to do with the imprecision of real numbers.
Testing real numbers for equality is fraught with problems,
since 0.95 may actually be seen in memory as 0.94999999999 or so.
(Oversimplified, but comparing one real number to another for equality just doesn't work reliably.)
:!:

Posted: Sun Mar 23, 2003 2:30 pm
by twigletmac
Having played around with the code I'd come to pretty much the same conclusion as Bill H as the following:

Code: Select all

<?php

for ($rangeDivisor = 0.85; round($rangeDivisor, 2) <= 0.95; $rangeDivisor += 0.01) { 
  echo $rangeDivisor;
  echo '<br />';
} 

?>
works as you'd expect but it would be more efficient not to run the round() function each time but instead to just do $rangeDivisor < 0.96.

Mac

Posted: Sun Mar 23, 2003 2:43 pm
by easyTree
ok, thanks for your prompt replies. I'd been preoccupied by the thought that I was falling foul of some kind of type-promotion effect that a php-n00b such as myself wouldn't know about..

doh!

:)