failing <= inside 'for ()'

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
easyTree
Forum Newbie
Posts: 2
Joined: Sun Mar 23, 2003 2:04 pm

failing <= inside 'for ()'

Post 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]
User avatar
twigletmac
Her Royal Site Adminness
Posts: 5371
Joined: Tue Apr 23, 2002 2:21 am
Location: Essex, UK

Post 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
Last edited by twigletmac on Sun Mar 23, 2003 2:31 pm, edited 1 time in total.
User avatar
Bill H
DevNet Resident
Posts: 1136
Joined: Sat Jun 01, 2002 10:16 am
Location: San Diego CA
Contact:

Post 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.)
:!:
User avatar
twigletmac
Her Royal Site Adminness
Posts: 5371
Joined: Tue Apr 23, 2002 2:21 am
Location: Essex, UK

Post 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
easyTree
Forum Newbie
Posts: 2
Joined: Sun Mar 23, 2003 2:04 pm

Post 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!

:)
Post Reply