home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / perl_mlb.zip / bigfloat.pl < prev    next >
Perl Script  |  1997-11-25  |  7KB  |  236 lines

  1. package bigfloat;
  2. require "bigint.pl";
  3. # Arbitrary length float math package
  4. #
  5. # by Mark Biggar
  6. #
  7. # number format
  8. #   canonical strings have the form /[+-]\d+E[+-]\d+/
  9. #   Input values can have inbedded whitespace
  10. # Error returns
  11. #   'NaN'           An input parameter was "Not a Number" or 
  12. #                       divide by zero or sqrt of negative number
  13. # Division is computed to 
  14. #   max($div_scale,length(dividend)+length(divisor)) 
  15. #   digits by default.
  16. # Also used for default sqrt scale
  17.  
  18. $div_scale = 40;
  19.  
  20. # Rounding modes one of 'even', 'odd', '+inf', '-inf', 'zero' or 'trunc'.
  21.  
  22. $rnd_mode = 'even';
  23.  
  24. #   bigfloat routines
  25. #
  26. #   fadd(NSTR, NSTR) return NSTR            addition
  27. #   fsub(NSTR, NSTR) return NSTR            subtraction
  28. #   fmul(NSTR, NSTR) return NSTR            multiplication
  29. #   fdiv(NSTR, NSTR[,SCALE]) returns NSTR   division to SCALE places
  30. #   fneg(NSTR) return NSTR                  negation
  31. #   fabs(NSTR) return NSTR                  absolute value
  32. #   fcmp(NSTR,NSTR) return CODE             compare undef,<0,=0,>0
  33. #   fround(NSTR, SCALE) return NSTR         round to SCALE digits
  34. #   ffround(NSTR, SCALE) return NSTR        round at SCALEth place
  35. #   fnorm(NSTR) return (NSTR)               normalize
  36. #   fsqrt(NSTR[, SCALE]) return NSTR        sqrt to SCALE places
  37.  
  38. # Convert a number to canonical string form.
  39. #   Takes something that looks like a number and converts it to
  40. #   the form /^[+-]\d+E[+-]\d+$/.
  41. sub main'fnorm { #(string) return fnum_str
  42.     local($_) = @_;
  43.     s/\s+//g;                               # strip white space
  44.     if (/^([+-]?)(\d*)(\.(\d*))?([Ee]([+-]?\d+))?$/
  45.       && ($2 ne '' || defined($4))) {
  46.     my $x = defined($4) ? $4 : '';
  47.     &norm(($1 ? "$1$2$x" : "+$2$x"), (($x ne '') ? $6-length($x) : $6));
  48.     } else {
  49.     'NaN';
  50.     }
  51. }
  52.  
  53. # normalize number -- for internal use
  54. sub norm { #(mantissa, exponent) return fnum_str
  55.     local($_, $exp) = @_;
  56.     if ($_ eq 'NaN') {
  57.     'NaN';
  58.     } else {
  59.     s/^([+-])0+/$1/;                        # strip leading zeros
  60.     if (length($_) == 1) {
  61.         '+0E+0';
  62.     } else {
  63.         $exp += length($1) if (s/(0+)$//);  # strip trailing zeros
  64.         sprintf("%sE%+ld", $_, $exp);
  65.     }
  66.     }
  67. }
  68.  
  69. # negation
  70. sub main'fneg { #(fnum_str) return fnum_str
  71.     local($_) = &'fnorm($_[$[]);
  72.     vec($_,0,8) ^= ord('+') ^ ord('-') unless $_ eq '+0E+0'; # flip sign
  73.     s/^H/N/;
  74.     $_;
  75. }
  76.  
  77. # absolute value
  78. sub main'fabs { #(fnum_str) return fnum_str
  79.     local($_) = &'fnorm($_[$[]);
  80.     s/^-/+/;                               # mash sign
  81.     $_;
  82. }
  83.  
  84. # multiplication
  85. sub main'fmul { #(fnum_str, fnum_str) return fnum_str
  86.     local($x,$y) = (&'fnorm($_[$[]),&'fnorm($_[$[+1]));
  87.     if ($x eq 'NaN' || $y eq 'NaN') {
  88.     'NaN';
  89.     } else {
  90.     local($xm,$xe) = split('E',$x);
  91.     local($ym,$ye) = split('E',$y);
  92.     &norm(&'bmul($xm,$ym),$xe+$ye);
  93.     }
  94. }
  95.  
  96. # addition
  97. sub main'fadd { #(fnum_str, fnum_str) return fnum_str
  98.     local($x,$y) = (&'fnorm($_[$[]),&'fnorm($_[$[+1]));
  99.     if ($x eq 'NaN' || $y eq 'NaN') {
  100.     'NaN';
  101.     } else {
  102.     local($xm,$xe) = split('E',$x);
  103.     local($ym,$ye) = split('E',$y);
  104.     ($xm,$xe,$ym,$ye) = ($ym,$ye,$xm,$xe) if ($xe < $ye);
  105.     &norm(&'badd($ym,$xm.('0' x ($xe-$ye))),$ye);
  106.     }
  107. }
  108.  
  109. # subtraction
  110. sub main'fsub { #(fnum_str, fnum_str) return fnum_str
  111.     &'fadd($_[$[],&'fneg($_[$[+1]));    
  112. }
  113.  
  114. # division
  115. #   args are dividend, divisor, scale (optional)
  116. #   result has at most max(scale, length(dividend), length(divisor)) digits
  117. sub main'fdiv #(fnum_str, fnum_str[,scale]) return fnum_str
  118. {
  119.     local($x,$y,$scale) = (&'fnorm($_[$[]),&'fnorm($_[$[+1]),$_[$[+2]);
  120.     if ($x eq 'NaN' || $y eq 'NaN' || $y eq '+0E+0') {
  121.     'NaN';
  122.     } else {
  123.     local($xm,$xe) = split('E',$x);
  124.     local($ym,$ye) = split('E',$y);
  125.     $scale = $div_scale if (!$scale);
  126.     $scale = length($xm)-1 if (length($xm)-1 > $scale);
  127.     $scale = length($ym)-1 if (length($ym)-1 > $scale);
  128.     $scale = $scale + length($ym) - length($xm);
  129.     &norm(&round(&'bdiv($xm.('0' x $scale),$ym),$ym),
  130.         $xe-$ye-$scale);
  131.     }
  132. }
  133.  
  134. # round int $q based on fraction $r/$base using $rnd_mode
  135. sub round { #(int_str, int_str, int_str) return int_str
  136.     local($q,$r,$base) = @_;
  137.     if ($q eq 'NaN' || $r eq 'NaN') {
  138.     'NaN';
  139.     } elsif ($rnd_mode eq 'trunc') {
  140.     $q;                         # just truncate
  141.     } else {
  142.     local($cmp) = &'bcmp(&'bmul($r,'+2'),$base);
  143.     if ( $cmp < 0 ||
  144.          ($cmp == 0 &&
  145.           ( $rnd_mode eq 'zero'                             ||
  146.            ($rnd_mode eq '-inf' && (substr($q,$[,1) eq '+')) ||
  147.            ($rnd_mode eq '+inf' && (substr($q,$[,1) eq '-')) ||
  148.            ($rnd_mode eq 'even' && $q =~ /[24680]$/)        ||
  149.            ($rnd_mode eq 'odd'  && $q =~ /[13579]$/)        )) ) {
  150.         $q;                     # round down
  151.     } else {
  152.         &'badd($q, ((substr($q,$[,1) eq '-') ? '-1' : '+1'));
  153.                     # round up
  154.     }
  155.     }
  156. }
  157.  
  158. # round the mantissa of $x to $scale digits
  159. sub main'fround { #(fnum_str, scale) return fnum_str
  160.     local($x,$scale) = (&'fnorm($_[$[]),$_[$[+1]);
  161.     if ($x eq 'NaN' || $scale <= 0) {
  162.     $x;
  163.     } else {
  164.     local($xm,$xe) = split('E',$x);
  165.     if (length($xm)-1 <= $scale) {
  166.         $x;
  167.     } else {
  168.         &norm(&round(substr($xm,$[,$scale+1),
  169.              "+0".substr($xm,$[+$scale+1,1),"+10"),
  170.           $xe+length($xm)-$scale-1);
  171.     }
  172.     }
  173. }
  174.  
  175. # round $x at the 10 to the $scale digit place
  176. sub main'ffround { #(fnum_str, scale) return fnum_str
  177.     local($x,$scale) = (&'fnorm($_[$[]),$_[$[+1]);
  178.     if ($x eq 'NaN') {
  179.     'NaN';
  180.     } else {
  181.     local($xm,$xe) = split('E',$x);
  182.     if ($xe >= $scale) {
  183.         $x;
  184.     } else {
  185.         $xe = length($xm)+$xe-$scale;
  186.         if ($xe < 1) {
  187.         '+0E+0';
  188.         } elsif ($xe == 1) {
  189.         &norm(&round('+0',"+0".substr($xm,$[+1,1),"+10"), $scale);
  190.         } else {
  191.         &norm(&round(substr($xm,$[,$xe),
  192.               "+0".substr($xm,$[+$xe,1),"+10"), $scale);
  193.         }
  194.     }
  195.     }
  196. }
  197.     
  198. # compare 2 values returns one of undef, <0, =0, >0
  199. #   returns undef if either or both input value are not numbers
  200. sub main'fcmp #(fnum_str, fnum_str) return cond_code
  201. {
  202.     local($x, $y) = (&'fnorm($_[$[]),&'fnorm($_[$[+1]));
  203.     if ($x eq "NaN" || $y eq "NaN") {
  204.     undef;
  205.     } else {
  206.     ord($y) <=> ord($x)
  207.     ||
  208.     (  local($xm,$xe,$ym,$ye) = split('E', $x."E$y"),
  209.          (($xe <=> $ye) * (substr($x,$[,1).'1')
  210.              || &bigint'cmp($xm,$ym))
  211.     );
  212.     }
  213. }
  214.  
  215. # square root by Newtons method.
  216. sub main'fsqrt { #(fnum_str[, scale]) return fnum_str
  217.     local($x, $scale) = (&'fnorm($_[$[]), $_[$[+1]);
  218.     if ($x eq 'NaN' || $x =~ /^-/) {
  219.     'NaN';
  220.     } elsif ($x eq '+0E+0') {
  221.     '+0E+0';
  222.     } else {
  223.     local($xm, $xe) = split('E',$x);
  224.     $scale = $div_scale if (!$scale);
  225.     $scale = length($xm)-1 if ($scale < length($xm)-1);
  226.     local($gs, $guess) = (1, sprintf("1E%+d", (length($xm)+$xe-1)/2));
  227.     while ($gs < 2*$scale) {
  228.         $guess = &'fmul(&'fadd($guess,&'fdiv($x,$guess,$gs*2)),".5");
  229.         $gs *= 2;
  230.     }
  231.     &'fround($guess, $scale);
  232.     }
  233. }
  234.  
  235. 1;
  236.