Classic Computer Magazine Archive COMPUTE! ISSUE 39 / AUGUST 1983 / PAGE 249

FORTH PAGE

Floating Point Division

Matt Ganis

The screen given below will create four new words three "helper" words and one main word). Here ???is a description of all four words:

1 TO 3 – This word will duplicate the value on top of the stack into the third position of the stack (note: the current third value becomes the fourth value; the current fourth value becomes the fifth value, etc.).

For example, if the stack looks like this:

[1231]
top bottom

A call to 1TO3 will leave the stack as follows:

[1213]
top bottom

QUOT – This word will compute and output the quotient of A/B. Also, the decimal point is output in this word (the 46 EMIT, is a decimal value of 46).

REMAIN – This word will output the next digit in the remainder. It should be understood that on each call only one digit is returned. Also, the 48 + converts the digit to ASCII code so that it can be printed instead of being popped off the stack with the . word.

FPDIV – This is the word that will be used when you want to divide two numbers (for example, 5 3 FPDIV will divide 5/3). In this example, FPDIV will return ten digits of the remainder (because of the 10/0 DO LOOP). If, for some reason, you want 100 digits in the remainder, simply change the 10 to a 100.

The value returned can't be used in a program. It is useful in that you may divide two numbers and obtain any precision that you desire.

Screen for the floating point division word.

For fig-FORTH or compatible FORTHs

SCR # 76
O
1 : 1TO3 DUP ROT SWAP ;
2
3 : QUOT 1T03 /MOD . 10 * SWAP
4 1TO3 46 EMIT ;
6 : REMAIN /MOD 48 + EMIT
7 10 * SWAP 1TO3 ;
8
9 ( **MAIN WORD IS 'FPDIV' *** )
10
11 : FPDIV DECIMAL QUOT 10 0 DO
12 REMAIN LOOP DROP DROP DROP ;
13
14 ;S
15

Make these changes if your /MOD works 'backwards':

: QUOT 1TO3 /MOD SWAP . 10 * SWAP
: REMAIN /MOD SWAP 48 + EMIT