加载中…
个人资料
  • 博客等级:
  • 博客积分:
  • 博客访问:
  • 关注人气:
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
正文 字体大小:

Tips 103:scalar 和 local 孰优孰劣

(2012-06-09 11:03:41)
标签:

local

scalar

stata

杂谈

分类: 简单编程

【问题】

local和scalar都可以保存某些数据。

除了引用时候一个需要引号,一个不需要,还有什么区别吗?

【手册】

which solution is better? There is certainly nothing to recommend one over the other in terms of program length—both programs have the same number of lines and, in fact, there is a one-to-one  correspondence between what each line does. Nevertheless, the scalar-based solution is better, and here is why:

Macros are printable representations of things. When we said local mean1 = r(mean), Stata took the contents of r(mean), converted them into a printable form from its internal (and highly accurate) binary representation, and stored that string of characters in the macro mean1. When we created mean2, Stata did the same thing again. Then when we said local diff = `mean1' - `mean2', Stata first substituted the contents of the macros mean1 and mean2—which are really strings—into the command. If the means of the two variables are 3 and 2, the printable string representations stored in mean1 and mean2 are “3” and “2”. After substitution, Stata processed the command local diff = 3- 2, converting the 3 and 2 back into internal binary representation to take the difference, producing the number 1, which it then converted into the printable representation “1”, which it finally stored in the macro diff.

All of this conversion from binary to printable representation and back again is a lot of work for Stata. Moreover, although there are no accuracy issues with numbers like 3 and 2, if the first number had been 3.67108239891*10-8, there would have been. When converting to printable form, Stata produces representations containing up to 17 digits and, if necessary, uses scientific notation. The first number would have become 3.6710823989e-08, and the last digit would have been lost. In computer scientific notation, 17 printable positions provides you with at least 13 significant digits.

This is a lot, but not as many as Stata carries internally. Now let’s trace the execution of the solution by using scalars. scalar m1 = r(mean) quickly copied the binary representation stored in r(mean) into the scalar m1. Similarly, executing scalar m2 = r(mean) did the same thing, although it saved it in m2. Finally, scalar df = m1 - m2 took the two binary representations, subtracted them, and copied the result to the scalar df. This produces a more accurate result.

【例子】

summarize var1, meanonly

scalar m1 = r(mean)

summarize var2, meanonly

scalar m2 = r(mean)

scalar df = m1 - m2

 

summarize var1, meanonly

local mean1 = r(mean)

summarize var2, meanonly

local mean2 = r(mean)

local diff = `mean1' - `mean2'

 

0

阅读 收藏 喜欢 打印举报/Report
  

新浪BLOG意见反馈留言板 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 产品答疑

新浪公司 版权所有