>> Home >> Resources & support >> FAQs >> The use of macros with the power operator

I coded `a'2 and got the wrong sign. Why?

Title   The use of macros with the power operator
Author William Gould, StataCorp

Be careful using macros with the power operator. Never code

        ... `a'^2 ...

Instead, code

        ... (`a')^2 ...

In particular, macros will surprise you when they contain negative numbers.

        . local a = -2

        . display `a'^2

To understand why this occurred, remember that macros substitute and think about what the line looked like after substitution.

  • `a' contains the text "−2".
  • Substitute "−2" for `a' in the text "display `a'^2"
  • The result is "display −2^2"

What do you think −22 should equal, 4 or −4? That depends on whether you take −22 to mean (−2)2 or −(22). Most people agree that −22 means −(22) and that the "right" answer is −4. Stata agrees with that:

        . display -2^2

You may agree that −22 = −4, but if a = −2, it is obvious that a2 should be 4 and that a2 should be 4 regardless of the sign of a. Stata agrees:

        . input a

          1. -2
          2.  2
          3. end

        . generate b = a^2

        . list

           |  a   b |
        1. | -2   4 |
        2. |  2   4 |

The problem is that macros such as `a' are not variables; they are substitutes. When you type "...`a'...", the contents of `a' are picked up and dropped right in its place in what you typed.

If you type `a'2 and `a' contains −2, then the result is −22, which, as we previously agreed, is −4.

The programming rule I use is always to bind `a' in parentheses — (`a') — when taking powers, and I do that whether `a' is a macro or a scalar. With scalars it is unnecessary; scalars are variables and negative two is stored whole in it:

        . scalar c = -2

        . display c^2

but I bind my scalars in parentheses anyway because I sometimes forget whether `a' is a macro or a scalar.

A note concerning Stata 4.0 and earlier

The danger of using `a'2 rather than (`a')2 did not exist in Stata 4 and earlier; it does exist in all modern Statas.

Older Statas took −22 to be (−2)2 or 4, and so coding `a'2 was perfectly safe. Interactive users, however, were shocked by this behavior, so we changed the way Stata works, and we made the change under version control so that old programs and ado-files continue to work:

        . display -2^2

        . version 4.0

        . display -2^2

As a programmer, I preferred Stata’s old way of working. That was, however, insufficient reason, because the old way made −22 produce 4, and that surprised interactive, nonprogramming users. The new way puts the confusing part back where it belongs, on programmers.





The Stata Blog: Not Elsewhere Classified Find us on Facebook Follow us on Twitter LinkedIn Google+ YouTube
© Copyright 1996–2017 StataCorp LLC   •   Terms of use   •   Privacy   •   Contact us