FOR Loops with different formats for control variable

For questions regarding programming in the EViews programming language.

Moderators: EViews Gareth, EViews Moderator, EViews Jason, EViews Matt

robmorea
Posts: 17
Joined: Wed Apr 16, 2014 3:06 am

FOR Loops with different formats for control variable

Postby robmorea » Thu Sep 03, 2015 8:58 am

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

EViews Gareth
Fe ddaethom, fe welon, fe amcangyfrifon
Posts: 13600
Joined: Tue Sep 16, 2008 5:38 pm

Re: FOR Loops with different formats for control variable

Postby EViews Gareth » Thu Sep 03, 2015 9:17 am

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.

robmorea
Posts: 17
Joined: Wed Apr 16, 2014 3:06 am

Re: FOR Loops with different formats for control variable

Postby robmorea » Thu Sep 03, 2015 9:39 am

Okay, it's clear. I'll use integers for the control variable.
Thank you Gareth.


Return to “Programming”

Who is online

Users browsing this forum: No registered users and 2 guests