Description: determine the square root of a number using an approximation method - ie, given a guess, divide the number we're trying to find the root for by the guess. Average this new number and the guess to get a new guess. Iterate, printing successive guesses until the root is found. Note that in order to check if the successive guesses are the same, I've had to make use of 2 conditional jumps and 2 jumps, such is the basic nature of the CJ instruction!
Input: number we want to find the square root for
Output: successive approximations for the square root
Memory registers used:
0 - number we want to find the square root for (call it 'a')
1 - current guess/estimate (call it 'g')
2- new guess/estimate (call it 'g2')
Program registers used: P 0 to P5
Target machines: Diehl Combitron-S, Combitronic
Note:
in the listing below 'snd' is the V symbol & 'rcv' is the same, but inverted, no modern symbol existing for it.
The code was reviewed by Udo in Germany who contacted me to point out that each program register can accept 10 characters only. I'd understood, incorrectly, that for example, the instruction J0, to jump to program register 0 counts as a single step and 10 such steps were permitted. Thanks Udo for getting in touch!
Instruction Comments
P 0 program register 0 - initialization
* clear +/- reg - omit?
1, clear x/: reg ? omit?
= as above
<number> input and print number we want to find sq root of - a. Program learning mode only?
#
snd send number - a - in Central Unit (CU) to memory register 0
0
1 initialize new guess - g2. Any number will do!
snd
2
P 1 program reg 1 - so we can jump back here
rcv receive number - g2 (new guess) - in CU
2
# print g2
snd g (current guess) now set to g2
1
rcv a in CU
0
: a: in x/: reg
rcv g in CU
1
P 2 program reg 2 (P1 full)
+ g in +/- reg
= a:g in CU
+ (a:g) + g in +/-
* (a:g) + g in CU
: ((a:g) + g): in x/:
2 ((a:g) + g):2 in CU - new guess, g2
=
snd g2
2
+ g2 in +/- reg
P 3 program reg 3 (P2 full)
rcv g in CU
1
- g2 - g in +/- reg
* g2 - g in CU
CJ g2 - g >=0 - jump to further check
4
J g2 - g <0 - repeat iteration
1
P 4 program reg 4 to check if g2 - g = 0
CHANGE_SIGN of CU content
CJ -(g2 - g) = g2 - g1 = 0, ie. g2 = g - jump to end program. Note - this may not actually occur and values may oscillate!
5
J -(g2 - g) < 0 - ie, g2 - g > 0 - repeat iteration
1
P 5 program reg 5
J go back to the beginning to calculate another square root. Could leave this out and end the program?
0
A end learning mode?