Notice: On April 23, 2014, Statalist moved from an email list to a forum, based at statalist.org.
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
RE: st: Loop question
From
Nick Cox <[email protected]>
To
"'[email protected]'" <[email protected]>
Subject
RE: st: Loop question
Date
Fri, 9 Dec 2011 11:46:25 +0000
Maarten's suggestion is consistent with mine, in that I deliberately did not recommend 0 0.6(0.1)1.1 as a -numlist-.
In this case, it would actually work more or less as you expect, as
. foreach i of num 0 0.6(0.1)1.1 {
2. di `i'
3. }
0
.6
.7
.8
.9
1
1.1
shows, but that's good luck. For more on the same point, see
SJ-10-1 pr0051 . . . . . . . . . . . . Stata tip 85: Looping over nonintegers
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . N. J. Cox
Q1/10 SJ 10(1):160--163 (no commands)
tip on using forvalues to loop over numbers
Nick
[email protected]
Maarten Buis
On Fri, Dec 9, 2011 at 12:03 PM, K Jensen <[email protected]> wrote:
> What is the easiest way of looping through one isolated value and a
> more conventional loop over a different range?
>
> Basically, I would like to do something like forvalues i=0 AND
> 0.6(0.1)1.1 except that this syntax doesn't exist. I.e. I would like
> i to take the values 0, 0.6, 0.7, 0.8, 0.9, 1.0, 1.1
*------------- begin example -------------
foreach i of numlist 0 6/11 {
local j = `i'/10
di `j'
}
*------------ end example -----------------
The direct answer is to use -foreach-.
The additional point here is the due to precision. The number 0.1
cannot be exactly represented in binary, just like the number 1/3
cannot be exactly represented in decimal. So computers work with an
approximation of 0.1, and that can show up in a loop, as in this case
you would repeatedly add up imperfect approximations of 0.1, which
will eventually lead to big enough deviations so that they might show
and cause trouble. So it is better to loop over the values 6/11, as
the value 1 (and other integers) can be exactly represented, and
within the loop divide that number by 10.
*
* For searches and help try:
* http://www.stata.com/help.cgi?search
* http://www.stata.com/support/statalist/faq
* http://www.ats.ucla.edu/stat/stata/