I am having a confusing experience with "forvalues." Using local macros, I need to define lower and upper bounds of some range (lb and ub respectively), divide the range by some integer (k) to get a "bandwidth" (bw=[ub-lb]/k) and execute forvalues i=`lb'(`bw')`ub' Logically is feels like it should increment i by bw until it gets to ub and then stop, resulting in k+1 values of i. Instead, for some values of lb and/or ub it stops one loop before it gets to ub. Below are the code and results for lb=10, k=5 and two different values of ub.
local lb=10
local ub=13
local bw=(`hi'-`lo')/5
forvalues i=`lb'(`bw')`ub' {
di `i'
}
gives me:
10
10.6
11.2
11.8
12.4
13
But if I set a different value of ub:
local lb=10
local ub=14
local bw=(`hi'-`lo')/5
forvalues i=`lb'(`bw')`ub' {
di `i'
}
gives me:
10
10.8
11.6
12.4
13.2
When ub=13 I get 6 values of i. When ub=14 I get 5 values of i.
Looking at some related threads I'm thinking this may have to do with the fact that Stata isn't actually working with precisely the numbers I'm expecting it to. For instance, it might be treating .8 as if it was actually .8000001, but telling me .8 to make me happy. Here's a clue: if, after calculating bw, I add a small amount to ub, the problem goes away:
local lb=10
local ub=14
local bw=(`hi'-`lo')/5
local ub=`ub'+.00001
forvalues i=`lb'(`bw')`ub' {
di `i'
}
gives me:
10
10.8
11.6
12.4
13.2
14
Which makes me think that it is incrementing by something a tiny bit more than .8.
Does that make sense? If so, is there a way to get it to loop the same number of times regardless of lb and ub? I don't care if the values of i aren't exactly precise, or if the last value of i is a tiny bit more than ub. I just need it to loop the same number of times. Any help would be very much appreciated.
0 Response to forvalues acting strangely
Post a Comment