Rational arithmetic

IMPLEMENTATION
A rational number is a string containing pair of integers U UI separated by blanks. U is numerator and UI is denominator of the rational number (U/UI). U and UI are relatively prime to each other and UI>0. The number zero is represented as 0 1.

 

ADDITION & SUBTRACTION FRACTIONS
 


FADD: procedure
parse arg U UI, V VI
D1 = GCD(UI, VI)
if D1 = 1 then return,
  LAST(U * VI + UI * V, UI * VI)
T = U * (VI / D1) + V * (UI / D1)
D2 = GCD(T, D1)
return LAST(T / D2, (UI / D1) * (VI / D2))

 

Where the LAST and GCD functions are (see as well as Euclid's GCD (and LCM) algorithm):

LAST & GCD


LAST: procedure
parse arg W1, W2
if W2 < 0
  then do
    W2 = ABS(W2); W1 = -W1
  end
D3 = GCD(W1, W2)
return (W1 / D3) (W2 / D3)
 
GCD: procedure
parse arg A, B
A = ABS(A)
do while B > 0
  parse value(B A//B) with A B
end
return A

 

MULTIPLICATION FRACTIONS
 


FMUL: procedure
parse arg U UI, V VI
UV = U * V; UIVI = UI * VI
D = GCD(UV, UIVI)
return LAST(UV / D, UIVI / D)

 

DIVISION FRACTIONS
 


FDIV: procedure
parse arg U UI, V VI
if V = 0 then
  call ERROR "FDIV - error divide by zero"
D1 = GCD(U, V); D2 = GCD(UI, VI)
return LAST((U / D1) * (VI / D2) *,
  SIGN(V), ABS((UI / D2) * (V / D1)))
 
ERROR: say ARG(1); exit

 

COMPARISON FRACTIONS

The FCOMP function returns -1 for (U/UI)<(V/VI), 0 for (U/UI)=(V/VI), and 1 for (U/UI)>(V/VI).  


FCOMP: procedure
parse arg U UI, V VI
return SIGN(U * VI - V * UI)

 

EXAMPLE
The program


say "(2/3) + (1/5) =" FWRITE(FADD(2 3, 1 5))
say "(3/4) - (2/5) =" FWRITE(FADD(3 4, -2 5))
say "(15/14) * (21/25) =",
    FWRITE(FMUL(15 14, 21 25))
say "(7/2) : (11/4) =" FWRITE(FDIV(7 2, 11 4))
exit
...
FWRITE: procedure
parse arg N D
return "(" || N || "/" || D || ")"

displays on the screen:


(2/3) + (1/5) = (13/15)
(3/4) - (2/5) = (7/20)
(15/14) * (21/25) = (9/10)
(7/2) : (11/4) = (14/11)

 

CONNECTIONS

Literature
Knuth D. E., Seminumerical Algorithms, vol. 2 of The Art of Computer Programming
Addison-Wesley, 1973


Cover Contents Index Main page Rexx page   Mail

last modified 4th August 2001
Copyright © 2000-2001 Vladimir Zabrodsky
Czech Republic