Next: Programming Tutorial Exercise 9, Previous: Programming Tutorial Exercise 7, Up: Answers to Exercises [Contents][Index]
The first step is to compute the derivative ‘f'(x)’ and thus the formula ‘x - f(x)/f'(x)’.
(Because this definition is long, it will be repeated in concise form below. You can use C-x * m to load it from there. While you are entering a Z ` Z ' body in a macro, Calc simply collects keystrokes without executing them. In the following diagrams we’ll pretend Calc actually executed the keystrokes as you typed them, just for purposes of illustration.)
2: sin(cos(x)) - 0.5 3: 4.5 1: 4.5 2: sin(cos(x)) - 0.5 . 1: -(sin(x) cos(cos(x))) . ' sin(cos(x))-0.5 RET 4.5 m r C-x ( Z ` TAB RET a d x RET
2: 4.5 1: x + (sin(cos(x)) - 0.5) / sin(x) cos(cos(x)) . / ' x RET TAB - t 1
Now, we enter the loop. We’ll use a repeat loop with a 20-repetition limit just in case the method fails to converge for some reason. (Normally, the Z / command will stop the loop before all 20 repetitions are done.)
1: 4.5 3: 4.5 2: 4.5 . 2: x + (sin(cos(x)) ... 1: 5.24196456928 1: 4.5 . . 20 Z < RET r 1 TAB s l x RET
This is the new guess for ‘x’. Now we compare it with the old one to see if we’ve converged.
3: 5.24196 2: 5.24196 1: 5.24196 1: 5.26345856348 2: 5.24196 1: 0 . . 1: 4.5 . . RET M-TAB a = Z / Z > Z ' C-x )
The loop converges in just a few steps to this value. To check the result, we can simply substitute it back into the equation.
2: 5.26345856348 1: 0.499999999997 . RET ' sin(cos($)) RET
Let’s test the new definition again:
2: x^2 - 9 1: 3.
1: 1 .
.
' x^2-9 RET 1 X
Once again, here’s the full Newton’s Method definition:
C-x ( Z ` TAB RET a d x RET / ' x RET TAB - t 1 20 Z < RET r 1 TAB s l x RET RET M-TAB a = Z / Z > Z ' C-x )
It turns out that Calc has a built-in command for applying a formula repeatedly until it converges to a number. See Nesting and Fixed Points, to see how to use it.
Also, of course, a R is a built-in command that uses Newton’s method (among others) to look for numerical solutions to any equation. See Root Finding.
Next: Programming Tutorial Exercise 9, Previous: Programming Tutorial Exercise 7, Up: Answers to Exercises [Contents][Index]