Page 1 of 1

FOR Loops with different formats for control variable

Posted: Thu Sep 03, 2015 8:58 am
by robmorea
Hello,

could you please help me to understand why Eviews has a different behaviour running for-next loops if I use different numeric formats for the control variable (i.e. the scalar that guides the loop iterations)?
For example, If I run the following program I get different result for scalars STEST1 and STEST2 (2 vs 3).
I expected to get 3 in both cases but in the first case the loop has only 2 iterations.

'test for loop
!CTR=1
FOR !J=0.1 TO 0.3 STEP 0.1
SCALAR STEST1=!CTR
!CTR=!CTR+1
NEXT

!CTR=1
FOR !J=1 TO 3 STEP 1
SCALAR STEST2=!CTR
!CTR=!CTR+1
NEXT
'end of program

Thanks a lot for you help,
Roberto

Re: FOR Loops with different formats for control variable

Posted: Thu Sep 03, 2015 9:17 am
by EViews Gareth
Computers don't handle decimals precisely. There is always a tiny bit of machine error when adding/subtracting/dividing/multiply decimals. To see this, look at the following example:

Code: Select all

!CTR=1 table a FOR !J=0.1 TO 0.4 STEP 0.1 SCALAR STEST1=!CTR a(!ctr,1) = !j !CTR=!CTR+1 NEXT show a
If you look at the value for 0.3, you can see it is actually a tiny bit larger than 0.3, which is why the for loop ends prematurely.

You are always better of using integers for the control variables on for loops.

Re: FOR Loops with different formats for control variable

Posted: Thu Sep 03, 2015 9:39 am
by robmorea
Okay, it's clear. I'll use integers for the control variable.
Thank you Gareth.