home *** CD-ROM | disk | FTP | other *** search
/ Usenet 1994 January / usenetsourcesnewsgroupsinfomagicjanuary1994.iso / sources / misc / volume24 / gnucalc / part34 < prev    next >
Encoding:
Text File  |  1991-10-31  |  55.5 KB  |  1,513 lines

  1. Newsgroups: comp.sources.misc
  2. From: daveg@synaptics.com (David Gillespie)
  3. Subject:  v24i082:  gnucalc - GNU Emacs Calculator, v2.00, Part34/56
  4. Message-ID: <1991Oct31.214526.2487@sparky.imd.sterling.com>
  5. X-Md4-Signature: 3fc5f7c3303aed7ac7de62e608e98d7b
  6. Date: Thu, 31 Oct 1991 21:45:26 GMT
  7. Approved: kent@sparky.imd.sterling.com
  8.  
  9. Submitted-by: daveg@synaptics.com (David Gillespie)
  10. Posting-number: Volume 24, Issue 82
  11. Archive-name: gnucalc/part34
  12. Environment: Emacs
  13. Supersedes: gmcalc: Volume 13, Issue 27-45
  14.  
  15. ---- Cut Here and unpack ----
  16. #!/bin/sh
  17. # do not concatenate these parts, unpack them in order with /bin/sh
  18. # file calc.texinfo continued
  19. #
  20. if test ! -r _shar_seq_.tmp; then
  21.     echo 'Please unpack part 1 first!'
  22.     exit 1
  23. fi
  24. (read Scheck
  25.  if test "$Scheck" != 34; then
  26.     echo Please unpack part "$Scheck" next!
  27.     exit 1
  28.  else
  29.     exit 0
  30.  fi
  31. ) < _shar_seq_.tmp || exit 1
  32. if test ! -f _shar_wnt_.tmp; then
  33.     echo 'x - still skipping calc.texinfo'
  34. else
  35. echo 'x - continuing file calc.texinfo'
  36. sed 's/^X//' << 'SHAR_EOF' >> 'calc.texinfo' &&
  37. has a maximum value at @cite{x = 1.19023}.  (The function also has a
  38. local @emph{minimum} at @cite{x = 0}.)
  39. X
  40. When we solved for @cite{x}, we got only one value even though
  41. @cite{34 - 24 x^2 = 0} is a quadratic equation that ought to have
  42. two solutions.  The reason is that @w{@kbd{a S}} normally returns a
  43. single ``principal'' solution.  If it needs to come up with an
  44. arbitrary sign (as occurs in the quadratic formula) it picks @cite{+}.
  45. If it needs an arbitrary integer, it picks zero.  We can get a full
  46. solution by pressing @kbd{H} (the Hyperbolic flag) before @kbd{a S}.
  47. X
  48. @group
  49. @smallexample
  50. 1:  34 - 24 x^2 = 0    1:  x = 1.19023 s1      1:  x = -1.19023
  51. X    .                      .                       .
  52. X
  53. X    r 3                    H a S x RET  s 5        1 n  s l s1 RET
  54. @end smallexample
  55. @end group
  56. X
  57. @noindent
  58. Calc has invented the variable @samp{s1} to represent an unknown sign;
  59. it is supposed to be either @i{+1} or @i{-1}.  Here we have used
  60. the ``let'' command to evaluate the expression when the sign is negative.
  61. If we plugged this into our second derivative we would get the same,
  62. negative, answer, so @cite{x = -1.19023} is also a maximum.
  63. X
  64. To find the actual maximum value, we must plug our two values of @cite{x}
  65. into the original formula.
  66. X
  67. @group
  68. @smallexample
  69. 2:  17 x^2 - 6 x^4 + 3    1:  24.08333 s1^2 - 12.04166 s1^4 + 3
  70. 1:  x = 1.19023 s1            .
  71. X    .
  72. X
  73. X    r 1 r 5                   s l RET
  74. @end smallexample
  75. @end group
  76. X
  77. @noindent
  78. (Here we see another way to use @kbd{s l}; if its input is an equation
  79. with a variable on the lefthand side, then @kbd{s l} treats the equation
  80. like an assignment to that variable if you don't give a variable name.)
  81. X
  82. It's clear that this will have the same value for either sign of
  83. @code{s1}, but let's work it out anyway, just for the exercise:
  84. X
  85. @group
  86. @smallexample
  87. 2:  [-1, 1]              1:  [15.04166, 15.04166]
  88. 1:  24.08333 s1^2 ...        .
  89. X    .
  90. X
  91. X  [ 1 n , 1 ] TAB            V M $ RET
  92. @end smallexample
  93. @end group
  94. X
  95. @noindent
  96. Here we have used a vector mapping operation to evaluate the function
  97. at several values of @samp{s1} at once.  @kbd{V M $} is like @kbd{V M '}
  98. except that it takes the formula from the top of the stack.  The
  99. formula is interpreted as a function to apply across the vector at the
  100. next-to-top stack level.  Since a formula on the stack can't contain
  101. @samp{$} signs, Calc assumes the variables in the formula stand for
  102. different arguments.  It prompts you for an @dfn{argument list}, giving
  103. the list of all variables in the formula in alphabetical order as the
  104. default list.  In this case the default is @samp{(s1)}, which is just
  105. what we want so we simply press @key{RET} at the prompt.
  106. X
  107. If there had been several different values, we could have used
  108. @w{@kbd{V R X}} to find the global maximum.
  109. X
  110. Calc has a built-in @kbd{a P} command that solves an equation using
  111. @w{@kbd{H a S}} and returns a vector of all the solutions.  It simply
  112. automates the job we just did by hand.  Applied to our original
  113. cubic polynomial, it would produce the vector of solutions
  114. @cite{[1.19023, -1.19023, 0]}.  (There is also an @kbd{a X} command
  115. which finds a local maximum of a function.  It uses a numerical search
  116. method rather than examining the derivatives, and thus requires you
  117. to provide some kind of initial guess to show it where to look.)
  118. X
  119. (@bullet{}) @strong{Exercise 2.}  Find the values for which the
  120. original formula @cite{17 x^2 - 6 x^4 + 3} is zero.  (There are
  121. four, two of which are complex numbers.)  Verify that these
  122. solutions are in fact correct.  @xref{Algebra Answer 2, 2}. (@bullet{})
  123. X
  124. The @kbd{m s} command enables ``symbolic mode,'' in which formulas
  125. like @samp{sqrt(5)} that can't be evaluated exactly are left in
  126. symbolic form rather than giving a floating-point approximate answer.
  127. Fraction mode (@kbd{m f}) is also useful when doing algebra.
  128. X
  129. @group
  130. @smallexample
  131. 2:  34 x - 24 x^3        2:  34 x - 24 x^3
  132. 1:  34 x - 24 x^3        1:  [sqrt(51) / 6, sqrt(51) / -6, 0]
  133. X    .                        .
  134. X
  135. X    r 2  RET     m s  m f    a P x RET
  136. @end smallexample
  137. @end group
  138. X
  139. One more mode that makes reading formulas easier is ``Big mode.''
  140. X
  141. @group
  142. @smallexample
  143. X               3
  144. 2:  34 x - 24 x
  145. X
  146. X      ____   ____
  147. X     V 51   V 51
  148. 1:  [-----, -----, 0]
  149. X       6     -6
  150. X
  151. X    .
  152. X
  153. X    d B
  154. @end smallexample
  155. @end group
  156. X
  157. Here things like powers, quotients and fractions, and square roots
  158. are displayed in a two-dimensional pictorial form.  Calc has other
  159. language modes as well, such as C mode, FORTRAN mode, and @TeX{} mode.
  160. X
  161. @group
  162. @smallexample
  163. 2:  34*x - 24*pow(x, 3)               2:  34*x - 24*x ** 3
  164. 1:  @{sqrt(51) / 6, sqrt(51) / -6, 0@}  1:  /sqrt(51) / 6, sqrt(51) / -6, 0/
  165. X    .                                     .
  166. X
  167. X    d C                                   d F
  168. X
  169. @end smallexample
  170. @end group
  171. @noindent
  172. @group
  173. @smallexample
  174. 3:  34 x - 24 x^3
  175. 2:  [@{\sqrt@{51@} \over 6@}, @{\sqrt@{51@} \over -6@}, 0]
  176. 1:  @{2 \over 3@} \sqrt@{5@}
  177. X    .
  178. X
  179. X    d T   ' 2 \sqrt@{5@} \over 3 RET
  180. @end smallexample
  181. @end group
  182. X
  183. @noindent
  184. As you can see, language modes affect both entry and display of
  185. formulas.  They affect such things as the names used for built-in
  186. functions, the set of arithmetic operators and their precedences,
  187. and notations for vectors and matrices.
  188. X
  189. Notice that @samp{sqrt(51)} may cause problems with older
  190. implementations of C and FORTRAN, which would require something more
  191. like @samp{sqrt(51.0)}.  It is always wise to check over the formulas
  192. produced by the various language modes to make sure they fully correct.
  193. X
  194. Type @kbd{m s}, @kbd{m f}, and @kbd{d N} to reset these modes.  (You
  195. may prefer to remain in Big mode, but all the examples in the tutorial
  196. are shown in normal mode.)
  197. X
  198. @cindex Area under a curve
  199. What is the area under the portion of this curve from @cite{x = 1} to @cite{2}?
  200. This is simply the integral of the function:
  201. X
  202. @group
  203. @smallexample
  204. 1:  17 x^2 - 6 x^4 + 3     1:  5.6666 x^3 - 1.2 x^5 + 3 x
  205. X    .                          .
  206. X
  207. X    r 1                        a i x
  208. @end smallexample
  209. @end group
  210. X
  211. @noindent
  212. We want to evaluate this at our two values for @cite{x} and subtract.
  213. One way to do it is again with vector mapping and reduction:
  214. X
  215. @group
  216. @smallexample
  217. 2:  [2, 1]            1:  [12.93333, 7.46666]    1:  5.46666
  218. 1:  5.6666 x^3 ...        .                          .
  219. X
  220. X   [ 2 , 1 ] TAB          V M $ RET                  V R -
  221. @end smallexample
  222. @end group
  223. X
  224. (@bullet{}) @strong{Exercise 3.}  Find the integral from 1 to @cite{y}
  225. of @c{$x \sin \pi x$}
  226. @w{@cite{x sin(pi x)}} (where the sine is calculated in radians).
  227. Find the values of the integral for integers @cite{y} from 1 to 5.
  228. @xref{Algebra Answer 3, 3}. (@bullet{})
  229. X
  230. Calc's integrator can do many simple integrals symbolically, but many
  231. others are beyond its capabilities.  Suppose we wish to find the area
  232. under the curve @c{$\sin x \ln x$}
  233. @cite{sin(x) ln(x)} over the same range of @cite{x}.  If
  234. you entered this formula and typed @kbd{a i x RET} (don't bother to try
  235. this), Calc would work for a long time but would be unable to find a
  236. solution.  In fact, there is no closed-form solution to this integral.
  237. Now what do we do?
  238. X
  239. @cindex Integration, numerical
  240. @cindex Numerical integration
  241. One approach would be to do the integral numerically.  It is not hard
  242. to do this by hand using vector mapping and reduction.  It is rather
  243. slow, though, since the sine and logarithm functions take a long time.
  244. We can save some time by reducing the working precision.
  245. X
  246. @group
  247. @smallexample
  248. 3:  10                  1:  [1, 1.1, 1.2,  ...  , 1.8, 1.9]
  249. 2:  1                       .
  250. 1:  0.1
  251. X    .
  252. X
  253. X 10 RET 1 RET .1 RET        C-u v x
  254. @end smallexample
  255. @end group
  256. X
  257. @noindent
  258. (Note that we have used the extended version of @kbd{v x}; we could
  259. also have used plain @kbd{v x} as follows:  @kbd{v x 10 RET 9 + .1 *}.)
  260. X
  261. @group
  262. @smallexample
  263. 2:  [1, 1.1, ... ]              1:  [0., 0.084941, 0.16993, ... ]
  264. 1:  sin(x) ln(x)                    .
  265. X    .
  266. X
  267. X    ' sin(x) ln(x) RET  s 1    m r  p 5 RET   V M $ RET
  268. X
  269. @end smallexample
  270. @end group
  271. @noindent
  272. @group
  273. @smallexample
  274. 1:  3.4195     0.34195
  275. X    .          .
  276. X
  277. X    V R +      0.1 *
  278. @end smallexample
  279. @end group
  280. X
  281. @noindent
  282. (If you got wildly different results, did you remember to switch
  283. to radians mode?)
  284. X
  285. Here we have divided the curve into ten segments of equal width;
  286. approximating these segments as rectangular boxes (i.e., assuming
  287. the curve is nearly flat at that resolution), we compute the areas
  288. of the boxes (height times width), then sum the areas.  (It is
  289. faster to sum first, then multiply by the width, since the width
  290. is the same for every box.)
  291. X
  292. The true value of this integral turns out to be about 0.374, so
  293. we're not doing too well.  Let's try another approach.
  294. X
  295. @group
  296. @smallexample
  297. 1:  sin(x) ln(x)    1:  0.84147 x - 0.84147 + 0.11957 (x - 1)^2 - ...
  298. X    .                   .
  299. X
  300. X    r 1                 a t x=1 RET 4 RET
  301. @end smallexample
  302. @end group
  303. X
  304. @noindent
  305. Here we have computed the Taylor series expansion of the function
  306. about the point @cite{x=1}.  We can now integrate this polynomial
  307. approximation, since polynomials are easy to integrate.
  308. X
  309. @group
  310. @smallexample
  311. 1:  0.42074 x^2 + ...    1:  [-0.0446, -0.42073]      1:  0.3761
  312. X    .                        .                            .
  313. X
  314. X    a i x RET            [ 2 , 1 ] TAB  V M $ RET         V R -
  315. @end smallexample
  316. @end group
  317. X
  318. @noindent
  319. Better!  By increasing the precision and/or asking for more terms
  320. in the Taylor series, we can get a result as accurate as we like.
  321. (Taylor series converge better away from singularities in the
  322. function such as the one at @code{ln(0)}, so it would also help to
  323. expand the series about the points @cite{x=2} or @cite{x=1.5} instead
  324. of @cite{x=1}.)
  325. X
  326. @cindex Simpson's rule
  327. @cindex Integration by Simpson's rule
  328. (@bullet{}) @strong{Exercise 4.}  Our first method approximated the
  329. curve by stairsteps of width 0.1; the total area was then the sum
  330. of the areas of the rectangles under these stairsteps.  Our second
  331. method approximated the function by a polynomial, which turned out
  332. to be a better approximation than stairsteps.  A third method is
  333. @dfn{Simpson's rule}, which is like the stairstep method except
  334. that the steps are not required to be flat.  Simpson's rule boils
  335. down to the formula,
  336. X
  337. @ifinfo
  338. @example
  339. (h/3) * (f(a) + 4 f(a+h) + 2 f(a+2h) + 4 f(a+3h) + ...
  340. X              + 2 f(a+(n-2)*h) + 4 f(a+(n-1)*h) + f(a+n*h))
  341. @end example
  342. @end ifinfo
  343. @tex
  344. \turnoffactive
  345. $$ \displaylines{{h \over 3} (f(a) + 4 f(a+h) + 2 f(a+2h) + 4 f(a+3h) + \cdots
  346. X   \hfill \cr \hfill    {} + 2 f(a+(n-2)h) + 4 f(a+(n-1)h) + f(a+n h))} $$
  347. @end tex
  348. X
  349. @noindent
  350. where @cite{n} (which must be even) is the number of slices and @cite{h}
  351. is the width of each slice.  These are 10 and 0.1 in our example.
  352. For reference, here is the corresponding equation for the stairstep
  353. method:
  354. X
  355. @ifinfo
  356. @example
  357. h * (f(a) + f(a+h) + f(a+2h) + f(a+3h) + ...
  358. X          + f(a+(n-2)*h) + f(a+(n-1)*h))
  359. @end example
  360. @end ifinfo
  361. @tex
  362. \turnoffactive
  363. $$ h (f(a) + f(a+h) + f(a+2h) + f(a+3h) + \cdots
  364. X           + f(a+(n-2)h) + f(a+(n-1)h)) $$
  365. @end tex
  366. X
  367. Compute the integral from 1 to 2 of @c{$\sin x \ln x$}
  368. @cite{sin(x) ln(x)} using
  369. Simpson's rule with 10 slices.  @xref{Algebra Answer 4, 4}. (@bullet{})
  370. X
  371. Calc has a built-in @kbd{a I} command for doing numerical integration.
  372. It uses @dfn{Romberg's method}, which is a more sophisticated cousin
  373. of Simpson's rule.  In particular, it knows how to keep refining the
  374. result until the current precision is satisfied.
  375. X
  376. @c [fix-ref Selecting Sub-Formulas]
  377. Aside from the commands we've seen so far, Calc also provides a
  378. large set of commands for operating on parts of formulas.  You
  379. indicate the desired sub-formula by placing the cursor on any part
  380. of the formula before giving a @dfn{selection} command.  Selections won't
  381. be covered in the tutorial; @pxref{Selecting Subformulas}, for
  382. details and examples.
  383. X
  384. @c hard exercise: simplify (2^(n r) - 2^(r*(n - 1))) / (2^r - 1) 2^(n - 1)
  385. @c                to 2^((n-1)*(r-1)).
  386. X
  387. @node Rewrites Tutorial, , Basic Algebra Tutorial, Algebra Tutorial
  388. @subsection Rewrite Rules
  389. X
  390. @noindent
  391. No matter how many built-in commands Calc provided for doing algebra,
  392. there would always be something you wanted to do that Calc didn't have
  393. in its repertoire.  So Calc also provides a @dfn{rewrite rule} system
  394. that you can use to define your own algebraic manipulations.
  395. X
  396. Suppose we want to simplify this trigonometric formula:
  397. X
  398. @group
  399. @smallexample
  400. 1:  1 / cos(x) - sin(x) tan(x)
  401. X    .
  402. X
  403. X    ' 1/cos(x) - sin(x) tan(x) RET   s 1
  404. @end smallexample
  405. @end group
  406. X
  407. @noindent
  408. If we were simplifying this by hand, we'd probably replace the
  409. @samp{tan} with a @samp{sin/cos} first, then combine over a common
  410. denominator.  There is no Calc command to do the former; the @kbd{j M}
  411. selection command will do the latter but we'll do both with rewrite
  412. rules just for practice.
  413. X
  414. Rewrite rules are written with the @samp{:=} symbol.
  415. X
  416. @group
  417. @smallexample
  418. 1:  1 / cos(x) - sin(x)^2 / cos(x)
  419. X    .
  420. X
  421. X    a r tan(a) := sin(a)/cos(a) RET
  422. @end smallexample
  423. @end group
  424. X
  425. @noindent
  426. (The ``assignment operator'' @samp{:=} has several uses in Calc.  All
  427. by itself the formula @samp{tan(a) := sin(a)/cos(a)} doesn't do anything,
  428. but when it is given to the @kbd{a r} command, that command interprets
  429. it as a rewrite rule.)
  430. X
  431. The lefthand side, @samp{tan(a)}, is called the @dfn{pattern} of the
  432. rewrite rule.  Calc searches the formula on the stack for parts that
  433. match the pattern.  Variables in a rewrite pattern are called
  434. @dfn{meta-variables}, and when matching the pattern each meta-variable
  435. can match any sub-formula.  Here, the meta-variable @samp{a} matched
  436. the actual variable @samp{x}.
  437. X
  438. When the pattern part of a rewrite rule matches a part of the formula,
  439. that part is replaced by the righthand side with all the meta-variables
  440. substituted with the things they matched.  So the result is
  441. @samp{sin(x) / cos(x)}.  Calc's normal algebraic simplifications then
  442. mix this in with the rest of the original formula.
  443. X
  444. To merge over a common denominator, we can use another simple rule:
  445. X
  446. @group
  447. @smallexample
  448. 1:  (1 - sin(x)^2) / cos(x)
  449. X    .
  450. X
  451. X    a r a/x + b/x := (a+b)/x RET
  452. @end smallexample
  453. @end group
  454. X
  455. This rule points out several interesting features of rewrite patterns.
  456. First, if a meta-variable appears several times in a pattern, it must
  457. match the same thing everywhere.  This rule detects common denominators
  458. because the same meta-variable @samp{x} is used in both of the
  459. denominators.
  460. X
  461. Second, meta-variable names are independent from variables in the
  462. target formula.  Notice that the meta-variable @samp{x} here matches
  463. the subformula @samp{cos(x)}; Calc never confuses the two meanings of
  464. @samp{x}.
  465. X
  466. And third, rewrite patterns know a little bit about the algebraic
  467. properties of formulas.  The pattern called for a sum of two quotients;
  468. Calc was able to match a difference of two quotients by matching
  469. @samp{a = 1}, @samp{b = -sin(x)^2}, and @samp{x = cos(x)}.
  470. X
  471. @c [fix-ref Algebraic Properties of Rewrite Rules]
  472. We could just as easily have written @samp{a/x - b/x := (a-b)/x} for
  473. the rule.  It would have worked just the same in all cases.  (If we
  474. really wanted the rule to apply only to @samp{+} or only to @samp{-},
  475. we could have used the @code{plain} symbol.  @xref{Algebraic Properties
  476. of Rewrite Rules}, for some examples of this.)
  477. X
  478. One more rewrite will complete the job.  We want to use the identity
  479. @samp{sin(x)^2 + cos(x)^2 = 1}, but of course we must first rearrange
  480. the identity in a way that matches our formula.  The obvious rule
  481. would be @samp{@w{1 - sin(x)^2} := cos(x)^2}, but a little thought shows
  482. that the rule @samp{sin(x)^2 := 1 - cos(x)^2} will also work.  The
  483. latter rule has a more general pattern so it will work in many other
  484. situations, too.
  485. X
  486. @group
  487. @smallexample
  488. 1:  (1 + cos(x)^2 - 1) / cos(x)           1:  cos(x)
  489. X    .                                         .
  490. X
  491. X    a r sin(x)^2 := 1 - cos(x)^2 RET          a s
  492. @end smallexample
  493. @end group
  494. X
  495. You may ask, what's the point of using the most general rule if you
  496. have to type it in every time anyway?  The answer is that Calc allows
  497. you to store a rewrite rule in a variable, then give the variable
  498. name in the @kbd{a r} command.  In fact, this is the preferred way to
  499. use rewrites.  For one, if you need a rule once you'll most likely
  500. need it again later.  Also, if the rule doesn't work quite right you
  501. can simply Undo, edit the variable, and run the rule again without
  502. having to retype it.
  503. X
  504. @group
  505. @smallexample
  506. ' tan(x) := sin(x)/cos(x) RET      s t tsc RET
  507. ' a/x + b/x := (a+b)/x RET         s t merge RET
  508. ' sin(x)^2 := 1 - cos(x)^2 RET     s t sinsqr RET
  509. X
  510. 1:  1 / cos(x) - sin(x) tan(x)     1:  cos(x)
  511. X    .                                  .
  512. X
  513. X    r 1                a r tsc RET  a r merge RET  a r sinsqr RET  a s
  514. @end smallexample
  515. @end group
  516. X
  517. To edit a variable, type @kbd{s e} and the variable name, use regular
  518. Emacs editing commands as necessary, then type @kbd{M-# M-#} or
  519. @kbd{C-c C-c} to store the edited value back into the variable.
  520. You can also use @w{@kbd{s e}} to create a new variable if you wish.
  521. X
  522. Notice that the first time you use each rule, Calc puts up a ``compiling''
  523. message briefly.  The pattern matcher converts rules into a special
  524. optimized pattern-matching language rather than using them directly.
  525. This allows @kbd{a r} to apply even rather complicated rules very
  526. efficiently.  If the rule is stored in a variable, Calc compiles it
  527. only once and stores the compiled form along with the variable.  That's
  528. another good reason to store your rules in variables rather than
  529. entering them on the fly.
  530. X
  531. (@bullet{}) @strong{Exercise 1.}  Type @kbd{m s} to get symbolic
  532. mode, then enter the formula @samp{@w{(2 + sqrt(2))} / @w{(1 + sqrt(2))}}.
  533. Using a rewrite rule, simplify this formula by multiplying both
  534. sides by the conjugate @w{@samp{1 - sqrt(2)}}.  The result will have
  535. to be expanded by the distributive law; do this with another
  536. rewrite.  @xref{Rewrites Answer 1, 1}. (@bullet{})
  537. X
  538. The @kbd{a r} command can also accept a vector of rewrite rules, or
  539. a variable containing a vector of rules.
  540. X
  541. @group
  542. @smallexample
  543. 1:  [tsc, merge, sinsqr]          1:  [tan(x) := sin(x) / cos(x), ... ]
  544. X    .                                 .
  545. X
  546. X    ' [tsc,merge,sinsqr] RET          =
  547. X
  548. @end smallexample
  549. @end group
  550. @noindent
  551. @group
  552. @smallexample
  553. 1:  1 / cos(x) - sin(x) tan(x)    1:  cos(x)
  554. X    .                                 .
  555. X
  556. X    s t trig RET  r 1                 a r trig RET  a s
  557. @end smallexample
  558. @end group
  559. X
  560. @c [fix-ref Nested Formulas with Rewrite Rules]
  561. Calc tries all the rules you give against all parts of the formula,
  562. repeating until no further change is possible.  (The exact order in
  563. which things are tried is rather complex, but for simple rules like
  564. the ones we've used here the order doesn't really matter.
  565. @xref{Nested Formulas with Rewrite Rules}.)
  566. X
  567. Calc actually repeats only up to 100 times, just in case your rule set
  568. has gotten into an infinite loop.  You can give a numeric prefix argument
  569. to @kbd{a r} to specify any limit.  In particular, @kbd{M-1 a r} does
  570. only one rewrite at a time.
  571. X
  572. @group
  573. @smallexample
  574. 1:  1 / cos(x) - sin(x)^2 / cos(x)    1:  (1 - sin(x)^2) / cos(x)
  575. X    .                                     .
  576. X
  577. X    r 1  M-1 a r trig RET                 M-1 a r trig RET
  578. @end smallexample
  579. @end group
  580. X
  581. You can type @kbd{M-0 a r} if you want no limit at all on the number
  582. of rewrites that occur.
  583. X
  584. Rewrite rules can also be @dfn{conditional}.  Simply follow the rule
  585. with a @samp{::} symbol and the desired condition.  For example,
  586. X
  587. @group
  588. @smallexample
  589. 1:  exp(2 pi i) + exp(3 pi i) + exp(4 pi i)
  590. X    .
  591. X
  592. X    ' exp(2 pi i) + exp(3 pi i) + exp(4 pi i) RET
  593. X
  594. @end smallexample
  595. @end group
  596. @noindent
  597. @group
  598. @smallexample
  599. 1:  1 + exp(3 pi i) + 1
  600. X    .
  601. X
  602. X    a r exp(k pi i) := 1 :: k % 2 = 0 RET
  603. @end smallexample
  604. @end group
  605. X
  606. @noindent
  607. (Recall, @samp{k % 2} is the remainder from dividing @samp{k} by 2,
  608. which will be zero only when @samp{k} is an even integer.)
  609. X
  610. An interesting point is that the variables @samp{pi} and @samp{i}
  611. were matched literally rather than acting as meta-variables.
  612. This is because they are special-constant variables.  The special
  613. constants @samp{e}, @samp{phi}, and so on also match literally.
  614. A common error with rewrite
  615. rules is to write, say, @samp{f(a,b,c,d,e) := g(a+b+c+d+e)}, expecting
  616. to match any @samp{f} with five arguments but in fact matching
  617. only when the fifth argument is literally @samp{e}!@refill
  618. X
  619. @cindex Fibonacci numbers
  620. @tindex fib
  621. Rewrite rules provide an interesting way to define your own functions.
  622. Suppose we want to define @samp{fib(n)} to produce the @var{n}th
  623. Fibonacci number.  The first two Fibonacci numbers are each 1;
  624. later numbers are formed by summing the two preceding numbers in
  625. the sequence.  This is easy to express in a set of three rules:
  626. X
  627. @group
  628. @smallexample
  629. ' [fib(1) := 1, fib(2) := 1, fib(n) := fib(n-1) + fib(n-2)] RET  s t fib
  630. X
  631. 1:  fib(7)               1:  13
  632. X    .                        .
  633. X
  634. X    ' fib(7) RET             a r fib RET
  635. @end smallexample
  636. @end group
  637. X
  638. One thing that is guaranteed about the order that rewrites are tried
  639. is that, for any given subformula, earlier rules in the rule set will
  640. be tried for that subformula before later ones.  So even though the
  641. first and third rules both match @samp{fib(1)}, we know the first will
  642. be used preferentially.
  643. X
  644. This rule set has one dangerous bug:  Suppose we apply it to the
  645. formula @samp{fib(x)}?  (Don't actually try this.)  The third rule
  646. will match @samp{fib(x)} and replace it with @w{@samp{fib(x-1) + fib(x-2)}}.
  647. Each of these will then be replaced to get @samp{fib(x-2) + 2 fib(x-3) +
  648. fib(x-4)}, and so on, expanding forever.  What we really want is to apply
  649. the third rule only when @samp{n} is an integer greater than two.  Type
  650. @w{@kbd{s e fib RET}}, then edit the third rule to:
  651. X
  652. @smallexample
  653. fib(n) := fib(n-1) + fib(n-2) :: integer(n) :: n > 2
  654. @end smallexample
  655. X
  656. @noindent
  657. Now:
  658. X
  659. @group
  660. @smallexample
  661. 1:  fib(6) + fib(x) + fib(0)      1:  8 + fib(x) + fib(0)
  662. X    .                                 .
  663. X
  664. X    ' fib(6)+fib(x)+fib(0) RET        a r fib RET
  665. @end smallexample
  666. @end group
  667. X
  668. @noindent
  669. We've created a new function, @code{fib}, and a new command,
  670. @w{@kbd{a r fib RET}}, which means ``evaluate all @code{fib} calls in
  671. this formula.''  To make things easier still, we can tell Calc to
  672. apply these rules automatically by storing them in the special
  673. variable @code{EvalRules}.
  674. X
  675. @group
  676. @smallexample
  677. 1:  [fib(1) := ...]    .                1:  [8, 13]
  678. X    .                                       .
  679. X
  680. X    s r fib RET        s t EvalRules RET    ' [fib(6), fib(7)] RET
  681. @end smallexample
  682. @end group
  683. X
  684. It turns out that this rule set has the problem that it does far
  685. more work than it needs to when @samp{n} is large.  Consider the
  686. first few steps of the computation of @samp{fib(6)}:
  687. X
  688. @group
  689. @smallexample
  690. fib(6) =
  691. fib(5)              +               fib(4) =
  692. fib(4)     +      fib(3)     +      fib(3)     +      fib(2) =
  693. fib(3) + fib(2) + fib(2) + fib(1) + fib(2) + fib(1) + 1 = ...
  694. @end smallexample
  695. @end group
  696. X
  697. @noindent
  698. Note that @samp{fib(3)} appears three times here.  Unless Calc's
  699. algebraic simplifier notices the multiple @samp{fib(3)}s and combines
  700. them (and, as it happens, it doesn't), this rule set does lots of
  701. needless recomputation.  To cure the problem, type @code{s e EvalRules}
  702. to edit the rules (or just @kbd{s E}, a shorthand command for editing
  703. @code{EvalRules}) and add another condition:
  704. X
  705. @smallexample
  706. fib(n) := fib(n-1) + fib(n-2) :: integer(n) :: n > 2 :: remember
  707. @end smallexample
  708. X
  709. @noindent
  710. If a @samp{:: remember} condition appears anywhere in a rule, then if
  711. that rule succeeds Calc will add another rule that describes that match
  712. to the front of the rule set.  (Remembering works in any rule set, but
  713. for technical reasons it is most effective in @code{EvalRules}.)  For
  714. example, if the rule rewrites @samp{fib(7)} to something that evaluates
  715. to 13, then the rule @samp{fib(7) := 13} will be added to the rule set.
  716. X
  717. Type @kbd{' fib(8) RET} to compute the eighth Fibonacci number, then
  718. type @kbd{s E} again to see what has happened to the rule set.
  719. X
  720. With the @code{remember} feature, our rule set can now compute
  721. @samp{fib(@var{n})} in just @var{n} steps.  In the process it builds
  722. up a table of all Fibonacci numbers up to @var{n}.  After we have
  723. computed the result for a particular @var{n}, we can get it back
  724. (and the results for all smaller @var{n}) later in just one step.
  725. X
  726. All Calc operations will run somewhat slower whenever @code{EvalRules}
  727. contains any rules.  You should type @kbd{s u EvalRules RET} now to
  728. un-store the variable.
  729. X
  730. (@bullet{}) @strong{Exercise 2.}  Sometimes it is possible to reformulate
  731. a problem to reduce the amount of recursion necessary to solve it.
  732. Create a rule that, in about @var{n} simple steps and without recourse
  733. to the @code{remember} option, replaces @samp{fib(@var{n}, 1, 1)} with
  734. @samp{fib(1, @var{x}, @var{y})} where @var{x} and @var{y} are the
  735. @var{n}th and @var{n+1}st Fibonacci numbers, respectively.  This rule is
  736. rather clunky to use, so add a couple more rules to make the ``user
  737. interface'' the same as for our first version: enter @samp{fib(@var{n})},
  738. get back a plain number.  @xref{Rewrites Answer 2, 2}. (@bullet{})
  739. X
  740. There are many more things that rewrites can do.  For example, there
  741. are @samp{&&&} and @samp{|||} pattern operators that create ``and''
  742. and ``or'' combinations of rules.  As one really simple example, we
  743. could combine our first two Fibonacci rules thusly:
  744. X
  745. @example
  746. [fib(1 ||| 2) := 1, fib(n) := ... ]
  747. @end example
  748. X
  749. @noindent
  750. That means ``@code{fib} of something matching either 1 or 2 rewrites
  751. to 1.''
  752. X
  753. You can also make meta-variables optional by enclosing them in @code{opt}.
  754. For example, the pattern @samp{a + b x} matches @samp{2 + 3 x} but not
  755. @samp{2 + x} or @samp{3 x} or @samp{x}.  The pattern @samp{opt(a) + opt(b) x}
  756. matches all of these forms, filling in a default of zero for @samp{a}
  757. and one for @samp{b}.
  758. X
  759. (@bullet{}) @strong{Exercise 3.}  Your friend Joe had @samp{2 + 3 x}
  760. on the stack and tried to use the rule
  761. @samp{opt(a) + opt(b) x := f(a, b, x)}.  What happened?
  762. @xref{Rewrites Answer 3, 3}. (@bullet{})
  763. X
  764. (@bullet{}) @strong{Exercise 4.}  Starting with an integer @cite{a},
  765. divide @cite{a} by two if it is even, otherwise compute @cite{3 a + 1}.
  766. Now repeat this step over and over.  A famous unproved conjecture
  767. is that for any starting @cite{a}, the sequence always eventually
  768. reaches 1.  Given the formula @samp{seq(@var{a}, 0)}, write a set of
  769. rules that convert this into @samp{seq(1, @var{n})} where @var{n}
  770. is the number of steps it took the sequence to reach the value 1.
  771. Now enhance the rules to accept @samp{seq(@var{a})} as a starting
  772. configuration, and to stop with just the number @var{n} by itself.
  773. Now make the result be a vector of values in the sequence, from @var{a}
  774. to 1.  (The formula @samp{@var{x}|@var{y}} appends the vectors @var{x}
  775. and @var{y}.)  For example, rewriting @samp{seq(6)} should yield the
  776. vector @cite{[6, 3, 10, 5, 16, 8, 4, 2, 1]}.
  777. @xref{Rewrites Answer 4, 4}. (@bullet{})
  778. X
  779. (@bullet{}) @strong{Exercise 5.}  Define, using rewrite rules, a function
  780. @samp{nterms(@var{x})} that returns the number of terms in the sum
  781. @var{x}, or 1 if @var{x} is not a sum.  (A @dfn{sum} for our purposes
  782. is one or more non-sum terms separated by @samp{+} or @samp{-} signs,
  783. so that @cite{2 - 3 (x + y) + x y} is a sum of three terms.)
  784. @xref{Rewrites Answer 5, 5}. (@bullet{})
  785. X
  786. (@bullet{}) @strong{Exercise 6.}  A Taylor series for a function is an
  787. infinite series that exactly equals the value of that function at
  788. values of @cite{x} near zero.
  789. X
  790. @ifinfo
  791. @example
  792. cos(x) = 1 - x^2 / 2! + x^4 / 4! - x^6 / 6! + ...
  793. @end example
  794. @end ifinfo
  795. @tex
  796. \turnoffactive \let\rm\goodrm
  797. $$ \cos x = 1 - {x^2 \over 2!} + {x^4 \over 4!} - {x^6 \over 6!} + \cdots $$
  798. @end tex
  799. X
  800. The @kbd{a t} command produces a @dfn{truncated Taylor series} which
  801. is obtained by dropping all the terms higher than, say, @cite{x^6}.
  802. Calc represents the truncated Taylor series as a polynomial in @cite{x}.
  803. Mathematicians often write a truncated series using a ``big-O'' notation
  804. that records what was the lowest term that was truncated.
  805. X
  806. @ifinfo
  807. @example
  808. cos(x) = 1 - x^2 / 2! + O(x^3)
  809. @end example
  810. @end ifinfo
  811. @tex
  812. \turnoffactive \let\rm\goodrm
  813. $$ \cos x = 1 - {x^2 \over 2!} + O(x^3) $$
  814. @end tex
  815. X
  816. @noindent
  817. The meaning of @cite{O(x^3)} is ``a quantity which is negligibly small
  818. if @cite{x^3} is considered negligibly small as @cite{x} goes to zero.''
  819. X
  820. The exercise is to create rewrite rules that simplify sums and products of
  821. power series represented as @samp{@var{polynomial} + O(@var{var}^@var{n})}.
  822. For example, given @samp{1 - x^2 / 2 + O(x^3)} and @samp{x - x^3 / 6 + O(x^4)}
  823. on the stack, we want to be able to type @kbd{*} and get the result
  824. @samp{x - 2:3 x^3 + O(x^4)}.  Don't worry if the terms of the sum are
  825. rearranged or if @kbd{a s} needs to be typed after rewriting.  (This one
  826. is rather tricky; the solution at the end of this chapter uses 6 rewrite
  827. rules.  Hint:  The @samp{constant(x)} condition tests whether @samp{x} is
  828. a number.)  @xref{Rewrites Answer 6, 6}. (@bullet{})
  829. X
  830. @c [fix-ref Rewrite Rules]
  831. @xref{Rewrite Rules}, for the whole story on rewrite rules.
  832. X
  833. @node Programming Tutorial, Answers to Exercises, Algebra Tutorial, Tutorial
  834. @section Programming Tutorial
  835. X
  836. @noindent
  837. The Calculator is written entirely in Emacs Lisp, a highly extensible
  838. language.  If you know Lisp, you can program the Calculator to do
  839. anything you like.  Rewrite rules also work as a powerful programming
  840. system.  But Lisp and rewrite rules take a while to master, and often
  841. all you want to do is define a new function or repeat a command a few
  842. times.  Calc has features that allow you to do these things easily.
  843. X
  844. One very limited form of programming is defining your own functions.
  845. Calc's @kbd{Z F} command allows you to define a function name and
  846. key sequence to correspond to any formula.  Programming commands use
  847. the shift-@kbd{Z} prefix; the user commands they create use the lower
  848. case @kbd{z} prefix.
  849. X
  850. @group
  851. @smallexample
  852. 1:  1 + x + x^2 / 2 + x^3 / 6         1:  1 + x + x^2 / 2 + x^3 / 6
  853. X    .                                     .
  854. X
  855. X    ' 1 + x + x^2/2! + x^3/3! RET         Z F e myexp RET RET RET y
  856. @end smallexample
  857. @end group
  858. X
  859. This polynomial is a Taylor series approximation to @samp{exp(x)}.
  860. The @kbd{Z F} command asks a number of questions.  The above answers
  861. say that the key sequence for our function should be @kbd{z e}; the
  862. @kbd{M-x} equivalent should be @code{calc-myexp}; the name of the
  863. function in algebraic formulas should be also be @code{myexp}; the
  864. default argument list @samp{(x)} is acceptable; and finally @kbd{y}
  865. answers the question ``leave it in symbolic form for non-constant
  866. arguments?''
  867. X
  868. @group
  869. @smallexample
  870. 1:  1.3495     2:  1.3495     3:  1.3495
  871. X    .          1:  1.34986    2:  1.34986
  872. X                   .          1:  myexp(a + 1)
  873. X                                  .
  874. X
  875. X    .3 z e         .3 E           ' a+1 RET z e
  876. @end smallexample
  877. @end group
  878. X
  879. First we call our new @code{exp} approximation with 0.3 as an
  880. argument, and compare it with the true @code{exp} function.  Then
  881. we note that, as requested, if we try to give @kbd{z e} an
  882. argument that isn't a plain number, it leaves the @code{myexp}
  883. function call in symbolic form.  If we had answered @kbd{n} to the
  884. final question, @samp{myexp(a + 1)} would have evaluated by plugging
  885. @samp{a + 1} in for @samp{x} in the defining formula.
  886. X
  887. @cindex Fresnel C(x) and S(x)
  888. (@bullet{}) @strong{Exercise 1.}  Fresnel's function @cite{C(x)} is
  889. defined by the integral of @samp{cos(pi t^2 / 2)} for @cite{t = 0} to
  890. @cite{x} in radians.  (It was invented because this integral has no
  891. solution in terms of basic functions; if you give it to Calc's @kbd{a i}
  892. command, it will ponder it for a long time and then give up.)  We can use
  893. the numerical integration command, however, which in algebraic notation
  894. is written like @samp{ninteg(f(t), t, 0, x)} with any integrand
  895. @samp{f(t)}.  Define a @kbd{z c} command and @code{fresC} function
  896. that implements this.  You will need to edit the default argument list
  897. a bit.  As a test, @samp{fresC(1)} should return 0.77989.  (Hint:
  898. @code{ninteg} will run a lot faster if you reduce the precision to, say,
  899. six digits beforehand.)  @xref{Programming Answer 1, 1}. (@bullet{})
  900. X
  901. (Calc doesn't have Fresnel functions built-in, but it does have the
  902. ``error function'' @samp{erf(x)}.  It turns out Fresnel's @cite{C(x)}
  903. and @cite{S(x)} (the same integral but with @code{sin} instead of
  904. @code{cos}) can be written in terms of @code{erf} and complex numbers
  905. as follows:  @samp{C(x) + i S(x) = (i+1) erf(sqrt(pi) (1-i) x / 2) / 2}.
  906. If you are curious, you could implement an alternate @kbd{z c} command
  907. that uses this method and compare the speeds of the two approaches.)
  908. X
  909. The simplest way to do real ``programming'' of Emacs is to define a
  910. @dfn{keyboard macro}.  A keyboard macro is simply a sequence of
  911. keystrokes which Emacs has stored away and can play back on demand.
  912. For example, if you find yourself typing @kbd{H a S x @key{RET}} often,
  913. you may wish to program a keyboard macro to type this for you.
  914. X
  915. @group
  916. @smallexample
  917. 1:  y = sqrt(x)          1:  x = y^2
  918. X    .                        .
  919. X
  920. X    ' y=sqrt(x) RET       C-x ( H a S x RET C-x )
  921. X
  922. 1:  y = cos(x)           1:  x = s1 arccos(y) + 2 pi n1
  923. X    .                        .
  924. X
  925. X    ' y=cos(x) RET           X
  926. @end smallexample
  927. @end group
  928. X
  929. @noindent
  930. When you type @kbd{C-x (}, Emacs begins recording.  But it is also
  931. still ready to execute your keystrokes, so you're really ``training''
  932. Emacs by walking it through the procedure once.  When you type
  933. @w{@kbd{C-x )}}, the macro is recorded.  You can now type @kbd{X} to
  934. re-execute the same keystrokes.
  935. X
  936. You can give a name to your macro by typing @kbd{Z K}.
  937. X
  938. @group
  939. @smallexample
  940. 1:  .              1:  y = x^4         1:  x = s2 sqrt(s1 sqrt(y))
  941. X                       .                   .
  942. X
  943. X  Z K x RET            ' y=x^4 RET         z x
  944. @end smallexample
  945. @end group
  946. X
  947. @noindent
  948. Notice that we use shift-@kbd{Z} to define the command, and lower-case
  949. @kbd{z} to call it up.
  950. X
  951. Keyboard macros can call other macros.
  952. X
  953. @group
  954. @smallexample
  955. 1:  abs(x)        1:  x = s1 y                1:  2 / x    1:  x = 2 / y
  956. X    .                 .                           .            .
  957. X
  958. X ' abs(x) RET   C-x ( ' y RET a = z x C-x )    ' 2/x RET       X
  959. @end smallexample
  960. @end group
  961. X
  962. (@bullet{}) @strong{Exercise 2.}  Define a keyboard macro to negate
  963. the item in level 3 of the stack, without disturbing the rest of
  964. the stack.  @xref{Programming Answer 2, 2}. (@bullet{})
  965. X
  966. (@bullet{}) @strong{Exercise 3.}  Define keyboard macros to compute
  967. the following functions:
  968. X
  969. @enumerate
  970. @item
  971. Compute @c{$\displaystyle{\sin x \over x}$}
  972. @cite{sin(x) / x}, where @cite{x} is the number on the
  973. top of the stack.
  974. X
  975. @item
  976. Compute the base-@cite{b} logarithm, just like the @kbd{B} key except
  977. the arguments are taken in the opposite order.
  978. X
  979. @item
  980. Produce a vector of integers from 1 to the integer on the top of
  981. the stack.
  982. @end enumerate
  983. @noindent
  984. @xref{Programming Answer 3, 3}. (@bullet{})
  985. X
  986. (@bullet{}) @strong{Exercise 4.}  Define a keyboard macro to compute
  987. the average (mean) value of a list of numbers.
  988. @xref{Programming Answer 4, 4}. (@bullet{})
  989. X
  990. In many programs, some of the steps must execute several times.
  991. Calc has @dfn{looping} commands that allow this.  Loops are useful
  992. inside keyboard macros, but actually work at any time.
  993. X
  994. @group
  995. @smallexample
  996. 1:  x^6          2:  x^6        1: 360 x^2
  997. X    .            1:  4             .
  998. X                     .
  999. X
  1000. X  ' x^6 RET          4         Z < a d x RET Z >
  1001. @end smallexample
  1002. @end group
  1003. X
  1004. @noindent
  1005. Here we have computed the fourth derivative of @cite{x^6} by
  1006. enclosing a derivative command in a ``repeat loop'' structure.
  1007. This structure pops a repeat count from the stack, then
  1008. executes the body of the loop that many times.
  1009. X
  1010. If you make a mistake while entering the body of the loop,
  1011. type @w{@kbd{Z C-g}} to cancel the loop command.
  1012. X
  1013. @cindex Fibonacci numbers
  1014. Here's another example:
  1015. X
  1016. @group
  1017. @smallexample
  1018. 3:  1               2:  10946
  1019. 2:  1               1:  17711
  1020. 1:  20                  .
  1021. X    .
  1022. X
  1023. 1 RET RET 20       Z < TAB C-j + Z >
  1024. @end smallexample
  1025. @end group
  1026. X
  1027. @noindent
  1028. The numbers in levels 2 and 1 should be the 21st and 22nd Fibonacci
  1029. numbers, respectively.  (To see what's going on, try a few repetitions
  1030. of the loop body by hand; @kbd{C-j}, also on the Line-Feed or @key{LFD}
  1031. key if you have one, makes a copy of the number in level 2.)
  1032. X
  1033. @cindex Golden ratio
  1034. @cindex Phi, golden ratio
  1035. A fascinating property of the Fibonacci numbers is that the @cite{n}th
  1036. Fibonacci number can be found directly by computing @c{$\phi^n / \sqrt{5}$}
  1037. @cite{phi^n / sqrt(5)}
  1038. and then rounding to the nearest integer, where @c{$\phi$ (``phi'')}
  1039. @cite{phi}, the
  1040. ``golden ratio,'' is @c{$(1 + \sqrt{5}) / 2$}
  1041. @cite{(1 + sqrt(5)) / 2}.  (For convenience, this constant is available
  1042. from the @code{phi} variable, or the @kbd{I H P} command.)
  1043. X
  1044. @group
  1045. @smallexample
  1046. 1:  1.61803         1:  24476.0000409    1:  10945.9999817    1:  10946
  1047. X    .                   .                    .                    .
  1048. X
  1049. X    I H P               21 ^                 5 Q /                R
  1050. @end smallexample
  1051. @end group
  1052. X
  1053. @cindex Continued fractions
  1054. (@bullet{}) @strong{Exercise 5.}  The @dfn{continued fraction}
  1055. representation of @c{$\phi$}
  1056. @cite{phi} is @c{$1 + 1/(1 + 1/(1 + 1/( \ldots )))$}
  1057. @cite{1 + 1/(1 + 1/(1 + 1/( ...@: )))}.
  1058. We can compute an approximate value by carrying this however far
  1059. and then replacing the innermost @c{$1/( \ldots )$}
  1060. @cite{1/( ...@: )} by 1.  Approximate
  1061. @c{$\phi$}
  1062. @cite{phi} using a twenty-term continued fraction.
  1063. @xref{Programming Answer 5, 5}. (@bullet{})
  1064. X
  1065. (@bullet{}) @strong{Exercise 6.}  Linear recurrences like the one for
  1066. Fibonacci numbers can be expressed in terms of matrices.  Given a
  1067. vector @w{@cite{[a, b]}} determine a matrix which, when multiplied by this
  1068. vector, produces the vector @cite{[b, c]}, where @cite{a}, @cite{b} and
  1069. @cite{c} are three successive Fibonacci numbers.  Now write a program
  1070. that, given an integer @cite{n}, computes the @cite{n}th Fibonacci number
  1071. using matrix arithmetic.  @xref{Programming Answer 6, 6}. (@bullet{})
  1072. X
  1073. @cindex Harmonic numbers
  1074. A more sophisticated kind of loop is the @dfn{for} loop.  Suppose
  1075. we wish to compute the 20th ``harmonic'' number, which is equal to
  1076. the sum of the reciprocals of the integers from 1 to 20.
  1077. X
  1078. @group
  1079. @smallexample
  1080. 3:  0               1:  3.597739
  1081. 2:  1                   .
  1082. 1:  20
  1083. X    .
  1084. X
  1085. 0 RET 1 RET 20         Z ( & + 1 Z )
  1086. @end smallexample
  1087. @end group
  1088. X
  1089. @noindent
  1090. The ``for'' loop pops two numbers, the lower and upper limits, then
  1091. repeats the body of the loop as an internal counter increases from
  1092. the lower limit to the upper one.  Just before executing the loop
  1093. body, it pushes the current loop counter.  When the loop body
  1094. finishes, it pops the ``step,'' i.e., the amount by which to
  1095. increment the loop counter.  As you can see, our loop always
  1096. uses a step of one.
  1097. X
  1098. This harmonic number function uses the stack to hold the running
  1099. total as well as for the various loop housekeeping functions.  If
  1100. you find this disorienting, you can sum in a variable instead:
  1101. X
  1102. @group
  1103. @smallexample
  1104. 1:  0         2:  1                  .            1:  3.597739
  1105. X    .         1:  20                                  .
  1106. X                  .
  1107. X
  1108. X    0 t 7       1 RET 20      Z ( & s + 7 1 Z )       r 7
  1109. @end smallexample
  1110. @end group
  1111. X
  1112. @noindent
  1113. The @kbd{s +} command adds the top-of-stack into the value in a
  1114. variable (and removes that value from the stack).
  1115. X
  1116. It's worth noting that many jobs that call for a ``for'' loop can
  1117. also be done more easily by Calc's high-level operations.  Two
  1118. other ways to compute harmonic numbers are to use vector mapping
  1119. and reduction (@kbd{v x 20}, then @w{@kbd{V M &}}, then @kbd{V R +}),
  1120. or to use the summation command @kbd{a +}.  Both of these are
  1121. probably easier than using loops.  However, there are some
  1122. situations where loops really are the way to go:
  1123. X
  1124. (@bullet{}) @strong{Exercise 7.}  Use a ``for'' loop to find the first
  1125. harmonic number which is greater than 4.0.
  1126. @xref{Programming Answer 7, 7}. (@bullet{})
  1127. X
  1128. Of course, if we're going to be using variables in our programs,
  1129. we have to worry about the programs clobbering values that the
  1130. caller was keeping in those same variables.  This is easy to
  1131. fix, though:
  1132. X
  1133. @group
  1134. @smallexample
  1135. X    .        1:  0.6667       1:  0.6667     3:  0.6667
  1136. X                 .                .          2:  3.597739
  1137. X                                             1:  0.6667
  1138. X                                                 .
  1139. X
  1140. X   Z `    p 4 RET 2 RET 3 /   s 7 s s a RET    Z '  r 7 s r a RET
  1141. @end smallexample
  1142. @end group
  1143. X
  1144. @noindent
  1145. When we type @kbd{Z `} (that's a back-quote character), Calc saves
  1146. its mode settings and the contents of the ten ``quick variables''
  1147. for later reference.  When we type @kbd{Z '} (that's an apostrophe
  1148. now), Calc restores those saved values.  Thus the @kbd{p 4} and
  1149. @kbd{s 7} commands have no effect outside this sequence.  Wrapping
  1150. this around the body of a keyboard macro ensures that it doesn't
  1151. interfere with what the user of the macro was doing.  Notice that
  1152. the contents of the stack, and the values of named variables,
  1153. survive past the @kbd{Z '} command.
  1154. X
  1155. @cindex Bernoulli numbers, approximate
  1156. The @dfn{Bernoulli numbers} are a sequence with the interesting
  1157. property that all of the odd Bernoulli numbers are zero, and the
  1158. even ones, while difficult to compute, can be roughly approximated
  1159. by the formula @c{$\displaystyle{2 n! \over (2 \pi)^n}$}
  1160. @cite{2 n!@: / (2 pi)^n}.  Let's write a keyboard
  1161. macro to compute (approximate) Bernoulli numbers.  (Calc has a
  1162. command, @kbd{k b}, to compute exact Bernoulli numbers, but
  1163. this command is very slow for large @cite{n} since the higher
  1164. Bernoulli numbers are very large fractions.)
  1165. X
  1166. @group
  1167. @smallexample
  1168. 1:  10               1:  0.0756823
  1169. X    .                    .
  1170. X
  1171. X    10     C-x ( RET 2 % Z [ DEL 0 Z : ' 2 $! / (2 pi)^$ RET = Z ] C-x )
  1172. @end smallexample
  1173. @end group
  1174. X
  1175. @noindent
  1176. You can read @kbd{Z [} as ``then,'' @kbd{Z :} as ``else,'' and
  1177. @kbd{Z ]} as ``end-if.''  There is no need for an explicit ``if''
  1178. command.  For the purposes of @w{@kbd{Z [}}, the condition is ``true''
  1179. if the value it pops from the stack is a nonzero number, or ``false''
  1180. if it pops zero or something that is not a number (like a formula).
  1181. Here we take our integer argument modulo 2; this will be nonzero
  1182. if we're asking for an odd Bernoulli number.
  1183. X
  1184. The actual tenth Bernoulli number is @cite{5/66}.
  1185. X
  1186. @group
  1187. @smallexample
  1188. 3:  0.0756823    1:  0          1:  0.25305    1:  0          1:  1.16659
  1189. 2:  5:66             .              .              .              .
  1190. 1:  0.0757575
  1191. X    .
  1192. X
  1193. 10 k b RET c f   M-0 DEL 11 X   DEL 12 X       DEL 13 X       DEL 14 X
  1194. @end smallexample
  1195. @end group
  1196. X
  1197. Just to exercise loops a bit more, let's compute a table of even
  1198. Bernoulli numbers.
  1199. X
  1200. @group
  1201. @smallexample
  1202. 3:  []             1:  [0.10132, 0.03079, 0.02340, 0.033197, ...]
  1203. 2:  2                  .
  1204. 1:  30
  1205. X    .
  1206. X
  1207. X [ ] 2 RET 30          Z ( X | 2 Z )
  1208. @end smallexample
  1209. @end group
  1210. X
  1211. @noindent
  1212. The vertical-bar @kbd{|} is the vector-concatenation command.  When
  1213. we execute it, the list we are building will be in stack level 2
  1214. (initially this is an empty list), and the next Bernoulli number
  1215. will be in level 1.  The effect is to append the Bernoulli number
  1216. onto the end of the list.  (To create a table of exact fractional
  1217. Bernoulli numbers, just replace @kbd{X} with @kbd{k b} in the above
  1218. sequence of keystrokes.)
  1219. X
  1220. With loops and conditionals, you can program essentially anything
  1221. in Calc.  One other command that makes looping easier is @kbd{Z /},
  1222. which takes a condition from the stack and breaks out of the enclosing
  1223. loop if the condition is true (non-zero).  You can use this to make
  1224. ``while'' and ``until'' style loops.
  1225. X
  1226. If you make a mistake when entering a keyboard macro, you can edit
  1227. it using @kbd{Z E}.  First, you must attach it to a key with @kbd{Z K}.
  1228. One technique is to enter a throwaway dummy definition for the macro,
  1229. then enter the real one in the edit command.
  1230. X
  1231. @group
  1232. @smallexample
  1233. 1:  3                   1:  3           Keyboard Macro Editor.
  1234. X    .                       .           Original keys: 1 RET 2 +
  1235. X
  1236. X                                        type "1\r"
  1237. X                                        type "2"
  1238. X                                        calc-plus
  1239. X
  1240. C-x ( 1 RET 2 + C-x )    Z K h RET      Z E h
  1241. @end smallexample
  1242. @end group
  1243. X
  1244. @noindent
  1245. This shows the screen display assuming you have the @file{macedit}
  1246. keyboard macro editing package installed, which is usually the case
  1247. since a copy of @file{macedit} comes bundled with Calc.
  1248. X
  1249. A keyboard macro is stored as a pure keystroke sequence.  The
  1250. @file{macedit} package (invoked by @kbd{Z E}) scans along the
  1251. macro and tries to decode it back into human-readable steps.
  1252. If a key or keys are simply shorthand for some command with a
  1253. @kbd{M-x} name, that name is shown.  Anything that doesn't correspond
  1254. to a @kbd{M-x} command is written as a @samp{type} command.
  1255. X
  1256. Let's edit in a new definition, for computing harmonic numbers.
  1257. First, erase the three lines of the old definition.  Then, type
  1258. in the new definition (or use Emacs @kbd{M-w} and @kbd{C-y} commands
  1259. to copy it from this page of the Info file; you can skip typing
  1260. the comments that begin with @samp{#}).
  1261. X
  1262. @smallexample
  1263. calc-kbd-push         # Save local values (Z `)
  1264. type "0"              # Push a zero
  1265. calc-store-into       # Store it in variable 1
  1266. type "1"
  1267. type "1"              # Initial value for loop
  1268. calc-roll-down        # This is the TAB key; swap initial & final
  1269. calc-kbd-for          # Begin "for" loop...
  1270. calc-inv              #   Take reciprocal
  1271. calc-store-plus       #   Add to accumulator
  1272. type "1"
  1273. type "1"              #   Loop step is 1
  1274. calc-kbd-end-for      # End "for" loop
  1275. calc-recall           # Now recall final accumulated value
  1276. type "1"
  1277. calc-kbd-pop          # Restore values (Z ')
  1278. @end smallexample
  1279. X
  1280. @noindent
  1281. Press @kbd{M-# M-#} to finish editing and return to the Calculator.
  1282. X
  1283. @group
  1284. @smallexample
  1285. 1:  20         1:  3.597739
  1286. X    .              .
  1287. X
  1288. X    20             z h
  1289. @end smallexample
  1290. @end group
  1291. X
  1292. If you don't know how to write a particular command in @file{macedit}
  1293. format, you can always write it as keystrokes in a @code{type} command.
  1294. There is also a @code{keys} command which interprets the rest of the
  1295. line as standard Emacs keystroke names.  In fact, @file{macedit} defines
  1296. a handy @code{read-kbd-macro} command which reads the current region
  1297. of the current buffer as a sequence of keystroke names, and defines that
  1298. sequence on the @kbd{X} (and @kbd{C-x e}) key.  Because this is so
  1299. useful, Calc puts this command on the @kbd{M-# m} key.  Try reading in
  1300. this macro in the following form:  Press @kbd{C-@@} (or @kbd{C-SPC}) at
  1301. one end of the text below, then type @kbd{M-# m} at the other.
  1302. X
  1303. @group
  1304. @example
  1305. Z ` 0 t 1
  1306. X    1 TAB
  1307. X    Z (  & s + 1  1 Z )
  1308. X    r 1
  1309. Z '
  1310. @end example
  1311. @end group
  1312. X
  1313. (@bullet{}) @strong{Exercise 8.}  A general algorithm for solving
  1314. equations numerically is @dfn{Newton's Method}.  Given the equation
  1315. @cite{f(x) = 0} for any function @cite{f}, and an initial guess
  1316. @cite{x_0} which is reasonably close to the desired solution, apply
  1317. this formula over and over:
  1318. X
  1319. @ifinfo
  1320. @example
  1321. new_x = x - f(x)/f'(x)
  1322. @end example
  1323. @end ifinfo
  1324. @tex
  1325. $$ x_{\goodrm new} = x - {f(x) \over f'(x)} $$
  1326. @end tex
  1327. X
  1328. @noindent
  1329. where @cite{f'(x)} is the derivative of @cite{f}.  The @cite{x}
  1330. values will quickly converge to a solution, i.e., eventually
  1331. @c{$x_{\rm new}$}
  1332. @cite{new_x} and @cite{x} will be equal to within the limits
  1333. of the current precision.  Write a program which takes a formula
  1334. involving the variable @cite{x}, and an initial guess @cite{x_0},
  1335. on the stack, and produces a value of @cite{x} for which the formula
  1336. is zero.  Use it to find a solution of @c{$\sin(\cos x) = 0.5$}
  1337. @cite{sin(cos(x)) = 0.5}
  1338. near @cite{x = 4.5}.  (Use angles measured in radians.)  Note that
  1339. the built-in @w{@kbd{a R}} (@code{calc-find-root}) command uses Newton's
  1340. method when it is able.  @xref{Programming Answer 8, 8}. (@bullet{})
  1341. X
  1342. @cindex Digamma function
  1343. @cindex Gamma constant, Euler's
  1344. @cindex Euler's gamma constant
  1345. (@bullet{}) @strong{Exercise 9.}  The @dfn{digamma} function @c{$\psi(z)$ (``psi'')}
  1346. @cite{psi(z)}
  1347. is defined as the derivative of @c{$\ln \Gamma(z)$}
  1348. @cite{ln(gamma(z))}.  For large
  1349. values of @cite{z}, it can be approximated by the infinite sum
  1350. X
  1351. @ifinfo
  1352. @example
  1353. psi(z) ~= ln(z) - 1/2z - sum(bern(2 n) / 2 n z^(2 n), n, 1, inf)
  1354. @end example
  1355. @end ifinfo
  1356. @tex
  1357. \let\rm\goodrm
  1358. $$ \psi(z) \approx \ln z - {1\over2z} -
  1359. X   \sum_{n=1}^\infty {\code{bern}(2 n) \over 2 n z^{2n}}
  1360. $$
  1361. @end tex
  1362. X
  1363. @noindent
  1364. where @c{$\sum$}
  1365. @cite{sum} represents the sum over @cite{n} from 1 to infinity
  1366. (or to some limit high enough to give the desired accuracy), and
  1367. the @code{bern} function produces (exact) Bernoulli numbers.
  1368. While this sum is not guaranteed to converge, in practice it is safe.
  1369. An interesting mathematical constant is Euler's gamma, which is equal
  1370. to about 0.5772.  One way to compute it is by the formula,
  1371. @c{$\gamma = -\psi(1)$}
  1372. @cite{gamma = -psi(1)}.  Unfortunately, 1 isn't a large enough argument
  1373. for the above formula to work (5 is a much safer value for @cite{z}).
  1374. Fortunately, we can compute @c{$\psi(1)$}
  1375. @cite{psi(1)} from @c{$\psi(5)$}
  1376. @cite{psi(5)} using
  1377. the recurrence @c{$\psi(z+1) = \psi(z) + {1 \over z}$}
  1378. @cite{psi(z+1) = psi(z) + 1/z}.  Your task:  Develop
  1379. a program to compute @c{$\psi(z)$}
  1380. @cite{psi(z)}; it should ``pump up'' @cite{z}
  1381. if necessary to be greater than 5, then use the above summation
  1382. formula.  Use looping commands to compute the sum.  Use your function
  1383. to compute @c{$\gamma$}
  1384. @cite{gamma} to twelve decimal places.  (Calc has a built-in command
  1385. for Euler's constant, @kbd{I P}, which you can use to check your answer.)
  1386. @xref{Programming Answer 9, 9}. (@bullet{})
  1387. X
  1388. @cindex Polynomial, list of coefficients
  1389. (@bullet{}) @strong{Exercise 10.}  Given a polynomial in @cite{x} and
  1390. a number @cite{m} on the stack, where the polynomial is of degree
  1391. @cite{m} or less (i.e., does not have any terms higher than @cite{x^m}),
  1392. write a program to convert the polynomial into a list-of-coefficients
  1393. notation.  For example, @cite{5 x^4 + (x + 1)^2} with @cite{m = 6}
  1394. should produce the list @cite{[1, 2, 1, 0, 5, 0, 0]}.  Also develop
  1395. a way to convert from this form back to the standard algebraic form.
  1396. @xref{Programming Answer 10, 10}. (@bullet{})
  1397. X
  1398. @cindex Recursion
  1399. (@bullet{}) @strong{Exercise 11.}  The @dfn{Stirling numbers of the
  1400. first kind} are defined by the recurrences,
  1401. X
  1402. @ifinfo
  1403. @example
  1404. s(n,n) = 1   for n >= 0,
  1405. s(n,0) = 0   for n > 0,
  1406. s(n+1,m) = s(n,m-1) - n s(n,m)   for n >= m >= 1.
  1407. @end example
  1408. @end ifinfo
  1409. @tex
  1410. \turnoffactive
  1411. $$ \eqalign{ s(n,n)   &= 1 \qquad \hbox{for } n \ge 0,  \cr
  1412. X             s(n,0)   &= 0 \qquad \hbox{for } n > 0, \cr
  1413. X             s(n+1,m) &= s(n,m-1) - n s(n,m) \qquad
  1414. X                          \hbox{for } n \ge m \ge 1.}
  1415. $$
  1416. (These numbers are also sometimes written $\displaystyle{n \brack m}$.)
  1417. @end tex
  1418. X
  1419. This can be implemented using a @dfn{recursive} program in Calc; the
  1420. program must invoke itself in order to calculate the two righthand
  1421. terms in the general formula.  Since it always invokes itself with
  1422. ``simpler'' arguments, it's easy to see that it will always
  1423. eventually finish the computation.  Recursion is a little
  1424. difficult with Emacs keyboard macros since the macro is executed
  1425. before its definition is complete.  So here's the recommended
  1426. strategy:  Create a ``dummy macro'' and assign it to a key with,
  1427. e.g., @kbd{Z K s}.  Now enter the true definition, using the
  1428. @kbd{z s} command to call itself recursively, then assign it to
  1429. the same key with @kbd{Z K s}.  Now the @kbd{z s} command will
  1430. run the complete recursive program.  (Another way is to use @w{@kbd{Z E}}
  1431. or @kbd{M-# m} (@code{read-kbd-macro}) to read the whole macro at once,
  1432. thus avoiding the ``training'' phase.)  The task:  Write a program
  1433. that computes Stirling numbers of the first kind, given @cite{n} and
  1434. @cite{m} on the stack.  Test it with @emph{small} inputs like
  1435. @cite{s(4,2)}.  (There is a built-in command for Stirling numbers,
  1436. @kbd{k s}, which you can use to check your answers.)
  1437. @xref{Programming Answer 11, 11}. (@bullet{})
  1438. X
  1439. The programming commands we've seen in this part of the tutorial
  1440. are low-level, general-purpose operations.  Often you will find
  1441. that a higher-level function, such as vector mapping or rewrite
  1442. rules, will do the job much more easily than a detailed, step-by-step
  1443. program can.
  1444. X
  1445. (@bullet{}) @strong{Exercise 12.}  Write another program for
  1446. computing Stirling numbers of the first kind, this time using
  1447. rewrite rules.  Once again, @cite{n} and @cite{m} should be taken
  1448. from the stack.  @xref{Programming Answer 12, 12}. (@bullet{})
  1449. X
  1450. @example
  1451. X
  1452. @end example
  1453. This ends the tutorial section of the Calc manual.  Now you know enough
  1454. about Calc to use it effectively for many kinds of calculations.  But
  1455. Calc has many features that were not even touched upon in this tutorial.
  1456. @c [not-split]
  1457. The rest of this manual tells the whole story.
  1458. @c [when-split]
  1459. @c Volume II of this manual, the @dfn{Calc Reference}, tells the whole story.
  1460. X
  1461. @page
  1462. @node Answers to Exercises, , Programming Tutorial, Tutorial
  1463. @section Answers to Exercises
  1464. X
  1465. @noindent
  1466. This section includes answers to all the exercises in the Calc tutorial.
  1467. X
  1468. @menu
  1469. * RPN Answer 1::           1 RET 2 RET 3 RET 4 + * -
  1470. * RPN Answer 2::           2*4 + 7*9.5 + 5/4
  1471. * RPN Answer 3::           Operating on levels 2 and 3
  1472. * RPN Answer 4::           Joe's complex problems
  1473. * Algebraic Answer 1::     Simulating Q command
  1474. * Algebraic Answer 2::     Joe's algebraic woes
  1475. * Algebraic Answer 3::     1 / 0
  1476. * Modes Answer 1::         3#0.1 = 3#0.0222222?
  1477. * Modes Answer 2::         16#f.e8fe15
  1478. * Modes Answer 3::         Joe's rounding bug
  1479. * Modes Answer 4::         Why floating point?
  1480. * Arithmetic Answer 1::    Why the \ command?
  1481. * Arithmetic Answer 2::    Tripping up the B command
  1482. * Vector Answer 1::        Normalizing a vector
  1483. * Vector Answer 2::        Average position
  1484. * Matrix Answer 1::        Row and column sums
  1485. * Matrix Answer 2::        Symbolic system of equations
  1486. * Matrix Answer 3::        Over-determined system
  1487. * List Answer 1::          Powers of two
  1488. * List Answer 2::          Least-squares fit with matrices
  1489. * List Answer 3::          Geometric mean
  1490. * List Answer 4::          Divisor function
  1491. * List Answer 5::          Duplicate factors
  1492. * List Answer 6::          Triangular list
  1493. * List Answer 7::          Another triangular list
  1494. * List Answer 8::          Maximum of Bessel function
  1495. * List Answer 9::          Integers the hard way
  1496. * List Answer 10::         All elements equal
  1497. * List Answer 11::         Estimating pi with darts
  1498. * List Answer 12::         Estimating pi with matchsticks
  1499. * List Answer 13::         Hash codes
  1500. SHAR_EOF
  1501. true || echo 'restore of calc.texinfo failed'
  1502. fi
  1503. echo 'End of  part 34'
  1504. echo 'File calc.texinfo is continued in part 35'
  1505. echo 35 > _shar_seq_.tmp
  1506. exit 0
  1507. exit 0 # Just in case...
  1508. -- 
  1509. Kent Landfield                   INTERNET: kent@sparky.IMD.Sterling.COM
  1510. Sterling Software, IMD           UUCP:     uunet!sparky!kent
  1511. Phone:    (402) 291-8300         FAX:      (402) 291-4362
  1512. Please send comp.sources.misc-related mail to kent@uunet.uu.net.
  1513.