Generalised floating point addition

From Rosetta Code
Revision as of 06:43, 30 July 2012 by Walterpachl (talk | contribs) (→‎any base: removed an empty line that caused a TSO hickup)
Generalised floating point addition is a draft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.

If possible, define addition for floating point numbers where the digits are stored in an arbitrary base. eg. the digits can be stored as binary, decimal, binary-coded decimal, or even balanced ternary.

Implement the code in a generalised form (such as a Template, Module or Mixin etc) that permits reusing of the code for different Bases.

If it is not possible to implement code in syntax of the specific language then:

  • note the reason.
  • perform test case using a built-in or external library.

Test case:

Use the Template to define Arbitrary precision addition on numbers stored in Binary Coded Decimal. Calculate the terms for -7 to 21 in this sequence of calculations:

Calculate the terms for -7 to 21 in this sequence of calculations
Number Term calculation Result
-7 12345679e63 × 81 + 1e63 1e72
-6 12345679012345679e54 × 81 + 1e54 1e72
-5 12345679012345679012345679e45 × 81 + 1e45 1e72
-4 12345679012345679012345679012345679e36 × 81 + 1e36 1e72
etc. The final calculation will be over 256 digits wide 1e72

Perform the multiplication of 81 by repeated additions. The results will always be 1e72.

Ideally the template should be able to successfully handle other bases - such as Balanced ternary - to perform the above test case.

ALGOL 68

Works with: ALGOL 68 version Revision 1 - one minor extension to language used - PRAGMA READ, similar to C's #include directive.
Works with: ALGOL 68G version Any - tested with release algol68g-2.3.3.

Note: This code stores the digits as array of digits with the "most significant digit" on the "left" as per normal "human" form. The net effect is that whole numbers (such as 100) are stored in the negative array positions, eg -2, -1 & 0, or [-2:0], And the fractional part of the floating point numbers are stored from index 1, eg. 1, 2, 3 etc. or [1:].

File: Template.Big_float.Addition.a68 - task code<lang algol68>########################################

  1. Define the basic addition operators #
  2. for the generalised base #
  1. derived DIGIT operators #

OP + = (DIGIT arg)DIGIT: arg; OP + = (DIGIT a,b)DIGIT: (DIGIT out := a; MOID(out +:= b); out);

  1. derived hybrid of DIGIT & DIGITS operators #

OP + = (DIGITS a, DIGIT b)DIGITS: a + INITDIGITS b; OP + = (DIGIT a, DIGITS b)DIGITS: INITDIGITS a + a; OP +:= = (REF DIGITS lhs, DIGIT arg)DIGITS: lhs := lhs + arg;

  1. derived DIGITS operators #

OP + = (DIGITS arg)DIGITS: arg; OP +:= = (REF DIGITS lhs, DIGITS arg)DIGITS: lhs := lhs + arg;

  1. TASK CODE #
  2. Actual generic addition operator #

OP + = (DIGITS a, b)DIGITS: (

 IF SIGN a = 0 THEN b ELIF SIGN b = 0 THEN a
 ELSE
   MODE SIGNED = DIGIT;
   INT extreme highest = MSD a MIN MSD b,
       overlap highest = MSD a MAX MSD b,
       overlap lowest  = LSD a MIN LSD b,
       extreme lowest  = LSD a MAX LSD b;
   SIGNED zero = ZERO LOC SIGNED;
   INT order = digit order OF arithmetic;
   DIGITS out;
   IF overlap highest > overlap lowest THEN # Either: NO overlapping digits #
     [extreme highest:extreme lowest]SIGNED a plus b;
  1. First: simply insert the known digits with their correct sign #
     a plus b[MSD a:LSD a] := a[@1];
     a plus b[MSD b:LSD b] := b[@1];
  1. Next: Zero any totally non overlapping digit #
     FOR place FROM overlap highest+order BY order TO overlap lowest-order
     DO a plus b[place] := zero OD;
  1. Finally: normalise by removing leading & trailing "zero" digit #
     out := INITDIGITS a plus b
   ELSE # Or: Add ALL overlapping digits #
     [extreme highest+(carry OF arithmetic|order|0):extreme lowest]SIGNED a plus b;
  1. First: Deal with the non overlapping Least Significant Digits #
     a plus b[overlap lowest-order:] := (LSD a > LSD b|a|b) [overlap lowest-order:];
  1. Or: Add any overlapping digits #
     SIGNED carry := zero;
     FOR place FROM overlap lowest BY order TO overlap highest DO
       SIGNED digit a = a[place], digit b = b[place];
       REF SIGNED result = a plus b[place];
       IF carry OF arithmetic THEN # used in big float #
         result := carry;
         carry := ( result +:= digit a );
         MOID( carry +:= ( result +:= (digit b) ) )
       ELSE
         result  := digit a;
         MOID( result +:= digit b )
       FI
     OD;
  1. Next: Deal with the non overlapping Most Significant digits #
     FOR place FROM overlap highest+order BY order TO extreme highest DO
       []DIGIT etc = (MSD a < MSD b|a|b);
       REF SIGNED result = a plus b[place];
       IF carry OF arithmetic THEN
         result := carry;
         carry := ( result +:= etc[place] )
       ELSE
         result := etc[place]
       FI
     OD;
  1. Next: Deal with the carry #
     IF carry OF arithmetic THEN
       a plus b[extreme highest+order] := carry
     FI;
  1. Finally: normalise by removing leading & trailing "zero" digits #
     out := INITDIGITS a plus b
   FI;
   out # EXIT #
 FI

);</lang>File: Template.Big_float.Base.a68 - task utility code<lang algol68># -*- coding: utf-8 -*- #

  1. Define the basic operators and routines for #
  2. manipulating DIGITS in a generalised base #

STRUCT (

 BOOL balanced,
      carry, # aka "carry" between digits #
 INT base,
     digit width,
     digit places,
     digit order,
 USTRING repr

) arithmetic := (

 FALSE, TRUE,
 10, 1, 81, -1, # Default is BCD/Hex #
 USTRING( # Note that the "circled" digits are negative - used in balance arithmetic #
          "ⓩ","ⓨ","ⓧ","ⓦ","ⓥ","ⓤ","ⓣ","ⓢ","ⓡ","ⓠ","ⓟ","ⓞ","ⓝ","ⓜ","ⓛ","ⓚ","ⓙ","ⓘ","ⓗ","ⓖ","ⓕ","ⓔ","ⓓ","ⓒ","ⓑ","ⓐ",
          "Ⓩ","Ⓨ","Ⓧ","Ⓦ","Ⓥ","Ⓤ","Ⓣ","Ⓢ","Ⓡ","Ⓠ","Ⓟ","Ⓞ","Ⓝ","Ⓜ","Ⓛ","Ⓚ","Ⓙ","Ⓘ","Ⓗ","Ⓖ","Ⓕ","Ⓔ","Ⓓ","Ⓒ","Ⓑ","Ⓐ",
                  "⑨","⑧","⑦","⑥","⑤","④","③","②","①",    "0",    "1","2","3","4","5","6","7","8","9",
          "A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z",
          "a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"
 )[@-(26*2+9)] # can print up to base 61, or balanced base 123 #

);

MODE DIGITS = FLEX[0]DIGIT;

  1. DIGIT OPerators #

OP INITDIGIT = (#LONG# INT i)DIGIT: (DIGIT out; digit OF out := #SHORTEN# i; out);

  1. OP INITDIGIT = (INT i)DIGIT: INITDIGIT LENG i;#

OP /= = (DIGIT a,b)BOOL: digit OF a /= digit OF b;

  1. Define additive and multiplicative identities #

OP ZERO = (DIGITS skip)DIGITS: INITDIGITS []DIGIT(ZERO LOC DIGIT),

  IDENTITY = (DIGITS skip)DIGITS: INITDIGITS []DIGIT(IDENTITY LOC DIGIT);

OP SIGN = (DIGIT digit)INT: SIGN digit OF digit;

  1. Define OPerators for Least and Most Significant DIGIT #

OP MSD = (DIGITS t)INT: LWB t,

  EXP = (DIGITS t)INT: digit order OF arithmetic * LWB t, # exponent #
  LSD = (DIGITS t)INT: UPB t;

OP INITDIGITS = (DIGIT in)DIGITS: INITDIGITS []DIGIT(in)[@0];

OP INITDIGITS = ([]DIGIT digits)DIGITS: (

      1. normalise digits:
 A) removed leading & trailing zeros
 B) IF not balanced arithmetic
    THEN make all digits positive and set sign bit FI
   MODE SIGNED = DIGIT;
   DIGIT zero = ZERO LOC DIGIT;
   DIGIT one = IDENTITY LOC DIGIT;
   DIGIT base digit = INITDIGIT base OF arithmetic;
   INT base = base OF arithmetic;
   INT half base = base % 2;
   INT order = digit order OF arithmetic;
   INT msd := LWB digits + int width*order, lsd := UPB digits; # XXX #
  1. create an array with some "extra" significant digits incase there is a "big" input value #
   [msd:lsd]SIGNED signed; signed[LWB digits:UPB digits] := digits[@1];
   FOR place FROM LWB signed TO LWB digits+order DO
     signed[place] := zero
   OD;
   IF msd + order /= lsd THEN
  1. Trim leading zeros #
     FOR place FROM msd BY -order TO lsd DO
       IF SIGN signed[place] /= 0 THEN msd := place; done msd FI
     OD;
     msd := lsd-order;
   done msd:
  1. Trim trailing zeros #
     FOR place FROM lsd BY order TO msd DO
       IF SIGN signed[place] /= 0 THEN lsd := place; done lsd FI
     OD;
     lsd := msd+order;
   done lsd:
     IF msd + order /= lsd THEN  # not zero #
       IF carry OF arithmetic THEN # Normalise to the "base OF arithmetic": #
         INT sign msd := SIGN digits[msd]; # first non zero digit #
         INT lwb digit := (balanced OF arithmetic|-half base|:sign msd < 0 |1-base|0);
         INT upb digit := (balanced OF arithmetic| half base|:sign msd > 0 |base-1|0);
         SIGNED carry := zero;
         FOR place FROM lsd BY order WHILE SIGN carry /=0 OR place >= LWB digits DO
            SIGNED digit := signed[place];
            carry := digit +:= carry;
            WHILE digit OF digit < lwb digit DO
              MOID(digit +:= base digit);
              MOID(carry -:= one)
            OD;
            WHILE digit OF digit > upb digit DO
              MOID(digit -:= base digit);
              MOID(carry +:= one)
            OD;
            signed[place] := digit; # normalised #
            IF SIGN digit /= 0 THEN msd := place FI
         OD
       FI
     FI;
     signed[msd:lsd][@msd]
   FI
 );
  1. re anchor the array with a shift #

OP SHL = (DIGITS in, INT shl)DIGITS: in[@MSD in-shl]; OP SHR = (DIGITS in, INT shr)DIGITS: in[@MSD in+shr];</lang>File: Template.Big_float_BCD.Base.a68 - test case code<lang algol68>################################################

  1. Define the basic operators and routines for #
  2. manipulating DIGITS specific to a BCD base #
  1. BCD noramlly means Binary Coded Decimal, but... #
  2. this code handles "Balanced Coded Data", meaning #
  3. Data can be in any numerical bases, and the data #
  4. can optionally be stored as Balanced about zero #
  1. define the basic axioms of the number system you are extending #

MODE DIGIT = STRUCT(#LONG# INT digit);

  1. Note: If the +:= and *:= operators for INT are being "overloaded",
       then it is sometimes necessary to wrap an INT in a STRUCT to
       protect the builtin definitions of the INT OPerators
  1. mixin the Big_float base definitions #

PR READ "Template.Big_float.Base.a68" PR

MODE BIGREAL = DIGITS;

  1. the Yoneda ambiguity forces the peculiar coercion n the body of OP #

OP ZERO = (DIGIT skip)DIGIT: (DIGIT out; digit OF out := 0; out); OP IDENTITY = (DIGIT skip)DIGIT: (DIGIT out; digit OF out := 1; out);

  1. define the basis operators #

OP ABS = (DIGIT a)INT: ABS digit OF a; OP - = (DIGIT a)DIGIT: INITDIGIT -digit OF a;

  1. Important: Operator +:= is required by Template_Big_float_addition. #
  2. Note: +:= returns carry DIGIT #

OP +:= = (REF DIGIT lhs, DIGIT arg)DIGIT: (

  1. Todo: Implement balanced arithmetic #
 INT sum = digit OF lhs + digit OF arg;   # arg may be -ve #
 INT carry := sum % base OF arithmetic;
 INT digit := sum - carry * base OF arithmetic;
 IF balanced OF arithmetic THEN
    INT half base = base OF arithmetic OVER 2;
    IF   digit > half base THEN
      digit -:= base OF arithmetic;
      carry +:= 1
    ELIF digit < -half base THEN
      digit +:= base OF arithmetic;
      carry -:= 1
    FI
 FI;
 lhs := INITDIGIT digit; INITDIGIT carry

);

INT half = base OF arithmetic OVER 2;

  1. ASSERT NOT balanced OF arithmetic OR ODD base OF arithmetic #
  2. Important: Operator *:= is required by Template_Big_float_multiplication. #
  3. Note: *:= returns carry DIGIT #

OP *:= = (REF DIGIT lhs, DIGIT arg)DIGIT: (

  1. Todo: Implement balanced arithmetic #
 INT product = digit OF lhs * digit OF arg;   # arg may be -ve #
 INT carry = product % base OF arithmetic;
 lhs := INITDIGIT(product - carry * base OF arithmetic);
 INITDIGIT carry

);

  1. Define the basic coersion/casting rules between types. #

OP INITLONGREAL = (BIGREAL a)LONG REAL:

 IF SIGN a = 0 THEN 0
 ELSE
   INT lsd a = LSD a; # Todo: Optimise/reduce to match "long real width" #
   LONG REAL out := digit OF a[MSD a];
   FOR place FROM MSD a - digit order OF arithmetic BY -digit order OF arithmetic TO lsd a DO
     out := out * base OF arithmetic + digit OF a[place]
   OD;
   out * LONG REAL(base OF arithmetic) ** -LSD a
 FI;

OP INITREAL = (BIGREAL r)REAL:

 SHORTEN INITLONGREAL r;

OP MSD = (LONG INT i)INT: (

 LONG INT remainder := i; INT count := 0;
 WHILE remainder /= 0 DO
   remainder %:= base OF arithmetic;
   MOID(count +:= 1)
 OD;
 count

);

OP INITBIGREAL = (LONG INT in int)BIGREAL: (

 INT max = MSD in int;
 [1-max:0]DIGIT out;
 LONG INT int := ABS in int;
 INT sign = SIGN in int;
 FOR place FROM UPB out BY digit order OF arithmetic TO LWB out WHILE int /= 0 DO
   INT digit := SHORTEN (int MOD base OF arithmetic);
   int := (int-digit) OVER base OF arithmetic;
   (digit OF out)[place] := sign * digit
 OD;

done:

 INITDIGITS out # normalise #

);

OP INITBIGREAL = (INT in int)BIGREAL:

 INITBIGREAL LENG in int;

OP INITBIGREAL = (LONG REAL in real)BIGREAL: (

 INT sign = SIGN in real;
 LONG REAL real := ABS in real;
 LONG REAL frac := real - ENTIER real;
 BIGREAL whole = INITBIGREAL ENTIER real; # normalised #
 INT base = base OF arithmetic,
     order = digit order OF arithmetic,
     lsd = digit places OF arithmetic; # Todo: can be optimised/reduced #
 
 [MSD whole:lsd]DIGIT out; out[MSD whole:LSD whole] := whole[@1];
 FOR place FROM LSD whole - order TO 0 DO out[place] := INITDIGIT 0 OD; # pad #
 FOR place FROM -order BY -order TO lsd DO
   frac *:= base;
   #LONG# INT digit := SHORTEN ENTIER frac;
   frac -:= digit;
   (digit OF out)[place] := digit;
   IF frac = 0 THEN done FI
 OD;

done:

 IF sign > 1 THEN INITDIGITS out ELSE - INITDIGITS out FI

);

OP INITBIGREAL = (REAL in real)BIGREAL:

 INITBIGREAL LENG in real;
  1. FORMAT digit fmt = $n(digit width OF arithmetic+ABS balanced OF arithmetic)(d)$;#

FORMAT big real fmt = $g((digit width OF arithmetic+ABS balanced OF arithmetic))","$;

OP REPR = (DIGIT digit)STRING:

 IF LWB repr OF arithmetic <= digit OF digit AND digit OF digit <= UPB repr OF arithmetic THEN
   (repr OF arithmetic)[digit OF digit]
 ELIF balanced OF arithmetic THEN
   whole(digit OF digit,digit width OF arithmetic+1)
 ELSE
   whole(digit OF digit,-digit width OF arithmetic)
 FI;

OP REPR = (BIGREAL real)STRING:(

 CHAR repr 0 = "0";
 STRING out;
 FOR place FROM MSD real BY -digit order OF arithmetic TO LSD real DO
   IF place = 1 AND place =  MSD real THEN out +:= "." FI;
   out +:= REPR(real[place]);
   IF place = 0 AND place /=  LSD real THEN out +:= "." FI
 OD;
 IF out = "" THEN out := repr 0 FI;
 IF SIGN real < 0 AND NOT balanced OF arithmetic THEN "-" +=: out FI;
 IF MSD real > 1 AND LSD real > 1 OR
    MSD real < 0 AND LSD real < 0 THEN
 # No decimal point yet, so maybe we need to add an exponent #
   out+IF digit order OF arithmetic*LSD real = 1 THEN repr 0
       ELSE "e"+REPR INITBIGREAL(digit order OF arithmetic*LSD real) FI
       # ELSE "E"+whole(digit order OF arithmetic*LSD real,0) FI #
 ELSE
   out
 FI

);</lang>File: Template.Big_float.Subtraction.a68 - bonus subtraction definitions<lang algol68>OP - = (DIGITS arg)DIGITS: (

 DIGITS out := arg;
 FOR digit FROM LSD arg BY digit order OF arithmetic TO MSD arg DO
   out[digit]:= -out[digit]
 OD;
 out

);

OP SIGN = (DIGITS arg)INT:

 IF LSD arg - MSD arg  = digit order OF arithmetic THEN 0 # empty array #
 ELSE # balanced artihmetic # SIGN arg[MSD arg] FI;

OP ABS = (DIGITS arg)DIGITS:

 IF SIGN arg < 0 THEN -arg ELSE arg FI;
  1. derived DIGIT operators #

OP - = (DIGIT a, b)DIGIT: a + -b; OP -:= = (REF DIGIT a, DIGIT b)DIGIT: a := a + -b;

  1. derived DIGITS operators #

OP - = (DIGITS a, b)DIGITS: a + -b; OP -:= = (REF DIGITS a, DIGITS b)DIGITS: a := a + -b;

  1. derived hybrid DIGIT and DIGITS operators #

OP - = (DIGITS a, DIGIT b)DIGITS: a - INITDIGITS b; OP - = (DIGIT a, DIGITS b)DIGITS: INITDIGITS a - a; OP -:= = (REF DIGITS lhs, DIGIT arg)DIGITS: lhs := lhs - arg;</lang>File: test.Big_float_BCD.Addition.a68 - test case code main program<lang algol68>#!/usr/local/bin/a68g --script #

  1. TEST CASE #
  2. A program to test abritary length BCD floating point addition. #

PR READ "prelude/general.a68" PR # rc:Template:ALGOL 68/prelude #

  1. READ Template for doing the actual arbitary precsion addition. #

PR READ "Template.Big_float.Addition.a68" PR

  1. include the basic axioms of the digits being used #

PR READ "Template.Big_float_BCD.Base.a68" PR PR READ "Template.Big_float.Subtraction.a68" PR

test: (

 BIGREAL pattern = INITBIGREAL 012345679,
 INT pattern width = 9;
 BIGREAL
   sum := INITBIGREAL 0,
   shifted pattern := pattern,
   shifted tiny := INITBIGREAL 1; # typically 0.000.....00001 etc #
 FOR term FROM -8 TO 20 DO
 # First make shifted pattern smaller by shifting right by the pattern width #
   shifted pattern := (shifted pattern)[@term*pattern width+2];
   shifted tiny := (shifted tiny)[@(term+1)*pattern width];
   MOID(sum +:= shifted pattern);
 # Manually multiply by 81 by repeated addition #
   BIGREAL prod := sum + sum + sum;
   MOID(prod +:= prod + prod);
   MOID(prod +:= prod + prod);
   MOID(prod +:= prod + prod);
   BIGREAL total = prod + shifted tiny;
   IF term < -4 THEN
     print(( REPR sum," x 81 gives: ", REPR prod, ", Plus ",REPR shifted tiny," gives: "))
   ELSE
     print((LSD prod - MSD prod + 1," digit test result: "))
   FI;
   printf(($g$, REPR total, $" => "b("Passed","Failed")"!"$, LSD total = MSD total, $l$))
 OD

)</lang>Output:

12345679e63 x 81 gives: 999999999e63, Plus 1e63 gives: 1e72 => Passed!
12345679012345679e54 x 81 gives: 999999999999999999e54, Plus 1e54 gives: 1e72 => Passed!
12345679012345679012345679e45 x 81 gives: 999999999999999999999999999e45, Plus 1e45 gives: 1e72 => Passed!
12345679012345679012345679012345679e36 x 81 gives: 999999999999999999999999999999999999e36, Plus 1e36 gives: 1e72 => Passed!
        +45 digit test result: 1e72 => Passed!
        +54 digit test result: 1e72 => Passed!
        +63 digit test result: 1e72 => Passed!
        +72 digit test result: 1e72 => Passed!
        +81 digit test result: 1e72 => Passed!
        +90 digit test result: 1e72 => Passed!
        +99 digit test result: 1e72 => Passed!
       +108 digit test result: 1e72 => Passed!
       +117 digit test result: 1e72 => Passed!
       +126 digit test result: 1e72 => Passed!
       +135 digit test result: 1e72 => Passed!
       +144 digit test result: 1e72 => Passed!
       +153 digit test result: 1e72 => Passed!
       +162 digit test result: 1e72 => Passed!
       +171 digit test result: 1e72 => Passed!
       +180 digit test result: 1e72 => Passed!
       +189 digit test result: 1e72 => Passed!
       +198 digit test result: 1e72 => Passed!
       +207 digit test result: 1e72 => Passed!
       +216 digit test result: 1e72 => Passed!
       +225 digit test result: 1e72 => Passed!
       +234 digit test result: 1e72 => Passed!
       +243 digit test result: 1e72 => Passed!
       +252 digit test result: 1e72 => Passed!
       +261 digit test result: 1e72 => Passed!

J

I am not currently able to implement the task exactly because I do not quite understand what is being asked for (nor why it would be useful).

That said, the task does specify some calculations to be performed.

Given

<lang j>e=: 2 : 0

 u * 10x ^ v

)</lang>

In other words, given a parse time word (e) which combines its two arguments as numbers, multiplying the number on its left by the exact exponent of 10 given on the right, I can do:

<lang> 1 e 63 + 12345679 e 63 * 81 1000000000000000000000000000000000000000000000000000000000000000000000000

  1 e 54 + 12345679012345679 e 54 * 81

1000000000000000000000000000000000000000000000000000000000000000000000000

  1 e 45 + 12345679012345679012345679x e 45 * 81

1000000000000000000000000000000000000000000000000000000000000000000000000

  1 e 36 + 12345679012345679012345679012345679x e 36 * 81

1000000000000000000000000000000000000000000000000000000000000000000000000</lang>

So, ok, let's turn this into a sequence:

<lang j>factor=: [: +/ [: 12345679 e ] _9 * 1 + i.&.(+&8) adjust=: 1 e (_9&*)</lang>

Here we show some examples of what these words mean:

<lang j> factor _4 NB. this is the number we multiply by 81 12345679012345679012345679012345679000000000000000000000000000000000000

  factor _3

12345679012345679012345679012345679012345679000000000000000000000000000

  factor 2 NB. here we see that we are using rational numbers

12345679012345679012345679012345679012345679012345679012345679012345679012345679012345679r1000000000000000000

  90j18 ":  factor 2  NB. formatted as decimal in 90 characters with 18 characters after the decimal point

12345679012345679012345679012345679012345679012345679012345679012345679.012345679012345679

  adjust _4  NB. this is the number we add to the result of multiplying our factor by 81

1000000000000000000000000000000000000

  adjust _3

1000000000000000000000000000</lang>

Given these words:

<lang j>

  _7+i.29 NB. these are the sequence elements we are going to generate

_7 _6 _5 _4 _3 _2 _1 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21

  #(adju + 81 * factor)&> _7+i.29 NB. we generate a sequence of 29 numbers

29

  ~.(adju + 81 * factor)&> _7+i.29  NB. here we see that they are all the same number

1000000000000000000000000000000000000000000000000000000000000000000000000</lang>

Note that ~. list returns the unique elements from that list.

REXX

base 10 only

<lang rexx>/*REXX pgm to perform generalized floating point addition using BCD nums*/

/*┌────────────────────────────────────────────────────────────────────┐ ┌─┘ This REXX program uses an uncompressed (or zoned) BCD which └─┐ │ consumes one byte for each represented digit. A leading sign (+ or -) │ │ is optional. An exponent is also allowed which is preceded by a ^. │ │ The value of the exponent may have a leading sign (+ or -). │ │ Each numeral (digit) is stored as its own character (gylph), as well │ │ as the signs and exponent indicator. There is essentially no limit on │ │ the number of digits in the mantissa or the exponent, but the value of │ │ the exponent is limited to around 16 million. The mantissa may also │ │ have a decimal point (.). │ │ │ │ Method: a table of twenty-eight BCD numbers is built, and a test case │ │ of adding that BCD number 81 tinmes (essentially multiplying by 81), │ │ and then a number is added to that sum, and the resultant sum should │ │ result in the final sum of 1e72 (for all cases). │ │ │ └─┐ The number of digits for the precision is automatically adjusted. ┌─┘

 └────────────────────────────────────────────────────────────────────┘*/

maxW=200-1 /*max width allowed for displays.*/

                                      /*ideally:   maxW=linesize()-1   */
                                      /*Not all REXXes have  LINESIZE. */

_123=012345679; reps=0; mult=63 /*used to construct test cases. */ say ' # addend uncompressed (zoned) BCD number' /*header.*/ say left('── ────── ─',maxW,'─') /*hdr sep*/

  do j=-7 to 21                       /*traipse through the test cases.*/
  reps=reps+1                         /*increase number of repititions.*/
  BCD.j=strip(copies(_123,reps)'^'mult,'L',0)    /*construct zoned BCD.*/
  if j//3==0 then BCD.J='+'BCD.j      /*add a leading + sign every 3rd#*/
  parse var BCD.j '^' pow             /*get the exponent part of the #.*/
  addend.j='1e'pow                    /*build the addend the hard way. */
  _=right(j,2) right(addend.j,6)      /*construct the prefix for a line*/
  aLine=_ BCD.j                       /*construct a line of output.    */
  if length(aLine)<maxW then say aLine     /*Fit on a line?  Display it*/
                        else say _ ' ['length(BCD.j) 'digits]'  /*other*/
  mult=mult-9                         /*decrease multiplier's exponent.*/
  maxDigs=length(BCD.j)+abs(pow)+5    /*compute max precision needed.  */
  if maxDigs>digits() then numeric digits maxDigs  /*inflate if needed.*/
  end    /*j*/

say copies('═',maxW) /*display a fence for seperation.*/ times=81 /*the number of times to add it. */

  do k=-7 to 21                       /*traipse through the test cases.*/
  parse var BCD.k mantissa '^' exponent  /*decompose the zoned BCD num.*/
  x=mantissa'e'exponent               /*reconstitute the original num. */
  sum=0                               /*prepare for the 81 additions.  */
              do times
              sum=sum+x               /*multiplying the hard way, yup! */
              end
  sum=(sum+addend.k)/1                /*a way to elide trailing zeroes.*/
  _=format(sum,,,,0)                  /*force sum ──►exponentional fmt.*/
  say right(k,3) 'sum='translate(_,"e",'E')   /*lets lowercase the  E. */
  end   /*k*/

exit /*stick a fork in it, we're done.*/</lang> output

 # addend               uncompressed (zoned) BCD number
── ────── ─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
-7   1e63 12345679^63
-6   1e54 +12345679012345679^54
-5   1e45 12345679012345679012345679^45
-4   1e36 12345679012345679012345679012345679^36
-3   1e27 +12345679012345679012345679012345679012345679^27
-2   1e18 12345679012345679012345679012345679012345679012345679^18
-1    1e9 12345679012345679012345679012345679012345679012345679012345679^9
 0    1e0 +12345679012345679012345679012345679012345679012345679012345679012345679^0
 1   1e-9 12345679012345679012345679012345679012345679012345679012345679012345679012345679^-9
 2  1e-18 12345679012345679012345679012345679012345679012345679012345679012345679012345679012345679^-18
 3  1e-27 +12345679012345679012345679012345679012345679012345679012345679012345679012345679012345679012345679^-27
 4  1e-36 12345679012345679012345679012345679012345679012345679012345679012345679012345679012345679012345679012345679^-36
 5  1e-45 12345679012345679012345679012345679012345679012345679012345679012345679012345679012345679012345679012345679012345679^-45
 6  1e-54 +12345679012345679012345679012345679012345679012345679012345679012345679012345679012345679012345679012345679012345679012345679^-54
 7  1e-63 12345679012345679012345679012345679012345679012345679012345679012345679012345679012345679012345679012345679012345679012345679012345679^-63
 8  1e-72 12345679012345679012345679012345679012345679012345679012345679012345679012345679012345679012345679012345679012345679012345679012345679012345679^-72
 9  1e-81 +12345679012345679012345679012345679012345679012345679012345679012345679012345679012345679012345679012345679012345679012345679012345679012345679012345679^-81
10  1e-90 12345679012345679012345679012345679012345679012345679012345679012345679012345679012345679012345679012345679012345679012345679012345679012345679012345679012345679^-90
11  1e-99 12345679012345679012345679012345679012345679012345679012345679012345679012345679012345679012345679012345679012345679012345679012345679012345679012345679012345679012345679^-99
12 1e-108 +12345679012345679012345679012345679012345679012345679012345679012345679012345679012345679012345679012345679012345679012345679012345679012345679012345679012345679012345679012345679^-108
13 1e-117  [193 digits]
14 1e-126  [202 digits]
15 1e-135  [212 digits]
16 1e-144  [220 digits]
17 1e-153  [229 digits]
18 1e-162  [239 digits]
19 1e-171  [247 digits]
20 1e-180  [256 digits]
21 1e-189  [266 digits]
═══════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════
 -7 sum=1e+72
 -6 sum=1e+72
 -5 sum=1e+72
 -4 sum=1e+72
 -3 sum=1e+72
 -2 sum=1e+72
 -1 sum=1e+72
  0 sum=1e+72
  1 sum=1e+72
  2 sum=1e+72
  3 sum=1e+72
  4 sum=1e+72
  5 sum=1e+72
  6 sum=1e+72
  7 sum=1e+72
  8 sum=1e+72
  9 sum=1e+72
 10 sum=1e+72
 11 sum=1e+72
 12 sum=1e+72
 13 sum=1e+72
 14 sum=1e+72
 15 sum=1e+72
 16 sum=1e+72
 17 sum=1e+72
 18 sum=1e+72
 19 sum=1e+72
 20 sum=1e+72
 21 sum=1e+72

any base

<lang rexx>/*REXX pgm to perform generalized floating point addition using BCD nums*/

/*┌────────────────────────────────────────────────────────────────────┐ ┌─┘ This REXX program uses an uncompressed (or zoned) BCD which └─┐ │ consumes one byte for each represented digit. A leading sign (+ or -) │ │ is optional. An exponent is also allowed which is preceded by a ^. │ │ The value of the exponent may have a leading sign (+ or -). │ │ Each numeral (digit) is stored as its own character (gylph), as well │ │ as the signs and exponent indicator. There is essentially no limit on │ │ the number of digits in the mantissa or the exponent, but the value of │ │ the exponent is limited to around 16 million. The mantissa may also │ │ have a decimal point (.). │ │ │ │ Method: a table of twenty-eight BCD numbers is built, and a test case │ │ of adding that BCD number 81 tinmes (essentially multiplying by 81), │ │ and then a number is added to that sum, and the resultant sum should │ │ result in the final sum of 1e72 (for all cases). │ │ │ │ The (input) numbers may be in any base; the REXX variable BASE │ │ (below) is the value of the base (radix) that the numbers are expressed│ │ in. │ └─┐ The number of digits for the precision is automatically adjusted. ┌─┘

 └────────────────────────────────────────────────────────────────────┘*/

maxW=200-1 /*max width allowed for displays.*/

                                      /*ideally:   maxW=linesize()-1   */
                                      /*Not all REXXes have  LINESIZE. */

base=10 /*radix that the numbers are in. */ _123=012345679; reps=0; mult=63 /*used to construct test cases. */ say ' # addend uncompressed (zoned) BCD number' /*header.*/ say left('── ────── ─',maxW,'─') /*hdr sep*/

  do j=-7 to 21                       /*traipse through the test cases.*/
  reps=reps+1                         /*increase number of repititions.*/
  BCD.j=strip(copies(_123,reps)'^'mult,'L',0)    /*construct zoned BCD.*/
  if j//3==0 then BCD.J='+'BCD.j      /*add a leading + sign every 3rd#*/
  parse var BCD.j '^' pow             /*get the exponent part of the #.*/
  addend.j='1e'pow                    /*build the addend the hard way. */
  _=right(j,2) right(addend.j,6)      /*construct the prefix for a line*/
  aLine=_ BCD.j                       /*construct a line of output.    */
  if length(aLine)<maxW then say aLine     /*Fit on a line?  Display it*/
                        else say _ ' ['length(BCD.j) 'digits]'  /*other*/
  mult=mult-9                         /*decrease multiplier's exponent.*/
  maxDigs=length(BCD.j)+abs(pow)+5    /*compute max precision needed.  */
  if maxDigs>digits() then numeric digits maxDigs  /*inflate if needed.*/
  end    /*j*/

say copies('═',maxW) /*display a fence for seperation.*/ times=81 /*the number of times to add it. */

  do k=-7 to 21                       /*traipse through the test cases.*/
  parse var BCD.k mantissa '^' pow    /*decompose the zoned BCD num.*/
  exp10=base(pow,,base)               /*convert the power to base 10.  */
  x=base(mantissa,,base) * 10**base(pow,,base)   /*express without a ^ */
  sum=0                               /*prepare for the 81 additions.  */
              do times
              sum=sum+x               /*multiplying the hard way, yup! */
              end
  sum=(sum+addend.k)/1                /*a way to elide trailing zeroes.*/
  _=format(sum,,,,0)                  /*force sum ──►exponentional fmt.*/
  _baseX=base(_/1,base)               /*this expresses  _ in base BASE.*/
  say right(k,3) 'sum='translate(_,"e",'E')   /*lets lowercase the  E. */
  end   /*k*/                         /*output is in base ten.         */

exit /*stick a fork in it, we're done.*/ /*──────────────────────────────────BASE subroutine─────────────────────*/ base: procedure; parse arg x 1 s 2 1 ox,tt,ii,left_,right_; f='BASE' @#=0123456789; @abc='abcdefghijklmnopqrstuvwxyz'; @abcu=@abc; upper @abcu $=$basex() /*char string of max base. */ m=length($)-1 /*"M" is the maximum base. */ c=left_\== | right_\== if tt== then tt=10 /*assume base 10 if omitted.*/ if ii== then ii=10 /*assume base 10 if omitted.*/ i=abs(ii) t=abs(tt) if t==999 | t=="*" then t=m if t>m & \c then call er81 t,2 m f'-to' if i>m then call er81 i,2 m f'-from'

if \c then do /*build char str for base ? */

          !=substr($,1+10*(tt<0),t)        /*character tring for base. */
          if tt<0 then !=0||!              /*prefix a zero if neg base.*/
          end

if x== then if c then return left_||t||right_

                  else return left(!,t)

@=substr($,1+10*(ii<0),i) /*@ =legal chars for base X.*/ oS= /*original sign placeholder.*/ if s='-' | s="+" then do /*process the sign (if any).*/

                     x=substr(x,2)         /*strip the sign character. */
                     oS=s                  /*save the original sign.   */
                     end

if (ii>10 & ii<37) | (ii<0 & ii>-27) then upper x /*uppercase it ? */

                                           /*if base 10, must be a num.*/

if pos('-',x)\==0 |, /*too many minus signs ? */

  pos('+',x)\==0 |,                        /*too many  plus signs ?    */
  x=='.'         |,                        /*is single decimal point ? */
  x==             then call er53 ox      /*or a single + or - sign ? */

parse var x w '.' g /*sep whole from fraction. */ if pos('.',g)\==0 then call er53 ox /*too many decimals points? */ items.1=0 /*# of whole part "digits". */ items.2=0 /*# of fractional "digits". */

if c then do /*any "digit" specifiers ? */

             do forever while w\==       /*process "whole" part.     */
             parse var w w.1 (left_) w.2 (right_) w
               do j=1 to 2;  if w.j\== then call putit w.j,1
               end
             end
             do forever while g\==       /*process fractional part.  */
             parse var g g.1 (left_) g.2 (right_) g
               do j=1 to 2;  if g.j\== then call putit g.j,2
               end
             end
         _=0;  p=0                         /*convert the whole # part. */
           do j=items.1 to 1 by -1;  _=_+item.1.j*(i**p)
           p=p+1                           /*increase power of the base*/
           end
         w=_;  _=0;  p=0                   /*convert fractional part.  */
           do j=1 to items.2;        _=_+item.2.j/i**p
           p=p+1                           /*increase power of the base*/
           end
         g=strip(strip(_,'L',0),,".")      /*strip leading dec point.  */
         if g=0 then g=                    /*no signifcant fract. part.*/
         end

__=w||g /*verify re-composed number.*/ _=verify(__,@'.') /*# have any unusual digits?*/ if _\==0 then call er48,ox,substr(__,_,1) '[for' f i"]" /*oops-sey.*/

if i\==10 then do /*convert # base I──►base 10*/

                                           /*...but only if not base 10*/
              _=0;  p=0                    /*convert the whole # part. */
                               do j=length(w) to 1 by -1 while w\==
                               _=_+((pos(substr(w,j,1),@)-1)*i**p)
                               p=p+1       /*increase power of the base*/
                               end
              w=_;  _=0;  p=1              /*convert fractional part.  */
                 do j=1 for length(g);_=_+((pos(substr(g,j,1),@)-1)/i**p)
                 p=p+1                     /*increase power of the base*/
                 end
              g=_
              end
         else if g\== then g="."g        /*reinsert period if needed.*/

if t\==10 then do /*convert base10 # to base T*/

              if w\== then do            /*convert whole number part.*/
                                   do j=1;   _=t**j;   if _>w then leave
                                   end
                             n=
                                 do k=j-1 to 1 by -1;   _=t**k;   d=w%_
                                 if c then n=n left_||d||right_
                                      else n=n||substr(!,1+d,1)
                                 w=w//_
                                 end
                             if c then w=n left_||w||right_
                                  else w=n||substr(!,1+w,1)
                             end
              if g\== then do;  n=       /*convert fractional part.  */
                                      do digits()+1;   if g==0 then leave
                                      p=g*t;    g=p//1;  d=trunc(p)
                                      if c then n=n left_||d||right_
                                           else n=n||substr(!,d+1,1)
                                      end
                             if n==0 then n=
                             if n\== then n='.'n   /*only a fraction?*/
                             g=n
                             end
              end

return oS||p(strip(space(w),'L',0)strip(strip(g,,0),"T",'.') 0)

/*═════════════════════════════general 1-line subs══════════════════════*/ $basex: return @#||@abcu||@abc||space(translate(,

       xrange('1'x,"fe"x),,@#'.+-'@abc||@abcu"0708090a0b0c0d"x),0)

er: say '***error!***'; say; say arg(1); say; exit 13 er48: call er arg(1) 'contains invalid characters:' arg(2) er53: call er arg(1) 'not numeric' er81: call er arg(1) 'must be in the range:' arg(2) isint: return datatype(arg(1),'W') isnum: return datatype(arg(1),'N') num: procedure; parse arg x .,f,q; if x== then return x

       if isnum(x) then return x/1; x=space(translate(x,,','),0)
       if isnum(x) then return x/1; return numnot()

numnot: if q==1 then return x; call er53 x numx: return num(arg(1),arg(2),1) p: return subword(arg(1),1,max(1,words(arg(1))-1)) putit: parse arg px,which;if \isint(px) then px=numx(px)

       items.which=items.which+1;  _=items.which; item.which._=px; return</lang>

output is identical to the previous version.