home *** CD-ROM | disk | FTP | other *** search
/ Power-Programmierung / CD1.mdf / modula2 / library / modula1 / power2.mod < prev    next >
Text File  |  1987-06-11  |  1KB  |  46 lines

  1. (* Compute a table of positive and negative powers of 2.  Exponents
  2.    range from 1 to 32. Do not truncate any digits! *)
  3.  
  4. MODULE powersof2;
  5.  
  6. FROM InOut IMPORT Write, WriteLn, WriteString, WriteCard;
  7.  
  8. CONST M = 11; (* M ~ N*log(2)*)
  9.       N = 32;
  10.  
  11. VAR i,j,k,exp,c,r,t: CARDINAL;
  12.     d: ARRAY [0..M] OF CARDINAL;
  13.     f: ARRAY [0..N] OF CARDINAL;
  14.  
  15. BEGIN
  16.   d[0] := 1; k := 1;
  17.   FOR exp := 1 TO N DO
  18.     (* compute d = 2^exp by d := 2*d *)
  19.     c := 0; (* carry *)
  20.     FOR i := 0 TO k-1 DO
  21.       t := 2*d[i] + c;
  22.       IF t >= 10 THEN
  23.         d[i] := t-10; c := 1;
  24.       ELSE
  25.         d[i] := t; c := 0;
  26.       END
  27.     END;
  28.     IF c > 0 THEN
  29.       d[k] := 1; INC(k);
  30.     END;
  31.     (* output d[k-1]...d[0] *)
  32.     i := M;
  33.     REPEAT DEC(i); Write(" ") UNTIL i = k;
  34.     REPEAT DEC(i); Write(CHR(d[i]+ORD('0'))) UNTIL i = 0;
  35.     WriteCard(exp,4);
  36.     (* compute and outputf = 2^(-exp) by f := f DIV 2 *)
  37.     WriteString(' 0.'); r := 0; (* remainder *)
  38.     FOR j := 1 TO exp-1 DO
  39.       r := 10*r + f[j]; f[j] := r DIV 2;
  40.       r := r MOD 2;
  41.       Write(CHR(f[j]+ORD('0')))
  42.     END;
  43.     f[exp] := 5; Write('5'); WriteLn
  44.   END
  45. END powersof2.
  46.