Announcement

Collapse
No announcement yet.
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • Issue with maximum bound of nested loops

    Dear Statalist members,

    There is a good chance I'm going crazy, but I have the following lines of code (I use Stata 13):

    ​forval a = -0.4(0.1)0.4 {
    forval b = -0.05(0.01)0.05 {
    forval c = -0.0015(0.0005)0.0015 {

    di "`a' ; `b'; `c'"



    }

    }

    }

    The outcome is that b never goes to 0.05, but only to 0.04. Any rational explanation of this?

    Many thanks in advance!

  • #2
    See -help precision-.

    The number 0.01 has no exact finite representation in binary. So you are not actually adding 0.01 each time: you are adding a close approximation:

    Code:
    display %21x 0.01
    Those little precision errors accumulate as you go through the loop, and by the time you get to what you would like to be 0.05, you are actually just a tad too high, so you have passed the upper bound specified.

    The solution is not to use floating point numbers in boundaries. So instead of

    Code:
    forvalues b = -0.05 (0.01) 0.05 {
    ...
    try
    Code:
    forvalues ib = -5 (1) 5 {
         local b = `ib'/100
         ....
    You still won't have `b' taking on the exact values you were hoping for--that just isn't possible no matter what you do--but you will at least get the right number of iterations through the loop.

    Comment


    • #3
      Puzzling enough at first sight to get its own Tip: http://www.stata-journal.com/sjpdf.h...iclenum=pr0051

      Comment


      • #4
        Thank you very much, gentlemen! The Stata Journal is an idispensable resource in general, but I never have the time to read it in detail.

        Comment

        Working...
        X