1 package Math::BigFloat;
5 use Exporter; # just for use to be happy
9 '+' => sub {new Math::BigFloat &fadd},
10 '-' => sub {new Math::BigFloat
11 $_[2]? fsub($_[1],${$_[0]}) : fsub(${$_[0]},$_[1])},
12 '<=>' => sub {new Math::BigFloat
13 $_[2]? fcmp($_[1],${$_[0]}) : fcmp(${$_[0]},$_[1])},
14 'cmp' => sub {new Math::BigFloat
15 $_[2]? ($_[1] cmp ${$_[0]}) : (${$_[0]} cmp $_[1])},
16 '*' => sub {new Math::BigFloat &fmul},
17 '/' => sub {new Math::BigFloat
18 $_[2]? scalar fdiv($_[1],${$_[0]}) :
19 scalar fdiv(${$_[0]},$_[1])},
20 'neg' => sub {new Math::BigFloat &fneg},
21 'abs' => sub {new Math::BigFloat &fabs},
25 0+ numify) # Order of arguments unsignificant
30 my ($foo) = fnorm(shift);
31 panic("Not a number initialized to Math::BigFloat") if $foo eq "NaN";
34 sub numify { 0 + "${$_[0]}" } # Not needed, additional overhead
35 # comparing to direct compilation based on
50 } elsif (abs($e) < $ln) {
51 substr($n, $ln + $e, 0) = '.';
53 $n = '.' . ("0" x (abs($e) - $ln)) . $n;
56 # 1 while $n =~ s/(.*\d)(\d\d\d)/$1,$2/;
63 # Rounding modes one of 'even', 'odd', '+inf', '-inf', 'zero' or 'trunc'.
67 sub fadd; sub fsub; sub fmul; sub fdiv;
68 sub fneg; sub fabs; sub fcmp;
69 sub fround; sub ffround;
72 # Convert a number to canonical string form.
73 # Takes something that looks like a number and converts it to
74 # the form /^[+-]\d+E[+-]\d+$/.
75 sub fnorm { #(string) return fnum_str
77 s/\s+//g; # strip white space
78 if (/^([+-]?)(\d*)(\.(\d*))?([Ee]([+-]?\d+))?$/ && "$2$4" ne '') {
79 &norm(($1 ? "$1$2$4" : "+$2$4"),(($4 ne '') ? $6-length($4) : $6));
85 # normalize number -- for internal use
86 sub norm { #(mantissa, exponent) return fnum_str
91 s/^([+-])0+/$1/; # strip leading zeros
92 if (length($_) == 1) {
95 $exp += length($1) if (s/(0+)$//); # strip trailing zeros
96 sprintf("%sE%+ld", $_, $exp);
102 sub fneg { #(fnum_str) return fnum_str
103 local($_) = fnorm($_[$[]);
104 vec($_,0,8) ^= ord('+') ^ ord('-') unless $_ eq '+0E+0'; # flip sign
110 sub fabs { #(fnum_str) return fnum_str
111 local($_) = fnorm($_[$[]);
117 sub fmul { #(fnum_str, fnum_str) return fnum_str
118 local($x,$y) = (fnorm($_[$[]),fnorm($_[$[+1]));
119 if ($x eq 'NaN' || $y eq 'NaN') {
122 local($xm,$xe) = split('E',$x);
123 local($ym,$ye) = split('E',$y);
124 &norm(Math::BigInt::bmul($xm,$ym),$xe+$ye);
129 sub fadd { #(fnum_str, fnum_str) return fnum_str
130 local($x,$y) = (fnorm($_[$[]),fnorm($_[$[+1]));
131 if ($x eq 'NaN' || $y eq 'NaN') {
134 local($xm,$xe) = split('E',$x);
135 local($ym,$ye) = split('E',$y);
136 ($xm,$xe,$ym,$ye) = ($ym,$ye,$xm,$xe) if ($xe < $ye);
137 &norm(Math::BigInt::badd($ym,$xm.('0' x ($xe-$ye))),$ye);
142 sub fsub { #(fnum_str, fnum_str) return fnum_str
143 fadd($_[$[],fneg($_[$[+1]));
147 # args are dividend, divisor, scale (optional)
148 # result has at most max(scale, length(dividend), length(divisor)) digits
149 sub fdiv #(fnum_str, fnum_str[,scale]) return fnum_str
151 local($x,$y,$scale) = (fnorm($_[$[]),fnorm($_[$[+1]),$_[$[+2]);
152 if ($x eq 'NaN' || $y eq 'NaN' || $y eq '+0E+0') {
155 local($xm,$xe) = split('E',$x);
156 local($ym,$ye) = split('E',$y);
157 $scale = $div_scale if (!$scale);
158 $scale = length($xm)-1 if (length($xm)-1 > $scale);
159 $scale = length($ym)-1 if (length($ym)-1 > $scale);
160 $scale = $scale + length($ym) - length($xm);
161 &norm(&round(Math::BigInt::bdiv($xm.('0' x $scale),$ym),$ym),
166 # round int $q based on fraction $r/$base using $rnd_mode
167 sub round { #(int_str, int_str, int_str) return int_str
168 local($q,$r,$base) = @_;
169 if ($q eq 'NaN' || $r eq 'NaN') {
171 } elsif ($rnd_mode eq 'trunc') {
174 local($cmp) = Math::BigInt::bcmp(Math::BigInt::bmul($r,'+2'),$base);
177 ( $rnd_mode eq 'zero' ||
178 ($rnd_mode eq '-inf' && (substr($q,$[,1) eq '+')) ||
179 ($rnd_mode eq '+inf' && (substr($q,$[,1) eq '-')) ||
180 ($rnd_mode eq 'even' && $q =~ /[24680]$/) ||
181 ($rnd_mode eq 'odd' && $q =~ /[13579]$/) )) ) {
184 Math::BigInt::badd($q, ((substr($q,$[,1) eq '-') ? '-1' : '+1'));
190 # round the mantissa of $x to $scale digits
191 sub fround { #(fnum_str, scale) return fnum_str
192 local($x,$scale) = (fnorm($_[$[]),$_[$[+1]);
193 if ($x eq 'NaN' || $scale <= 0) {
196 local($xm,$xe) = split('E',$x);
197 if (length($xm)-1 <= $scale) {
200 &norm(&round(substr($xm,$[,$scale+1),
201 "+0".substr($xm,$[+$scale+1,1),"+10"),
202 $xe+length($xm)-$scale-1);
207 # round $x at the 10 to the $scale digit place
208 sub ffround { #(fnum_str, scale) return fnum_str
209 local($x,$scale) = (fnorm($_[$[]),$_[$[+1]);
213 local($xm,$xe) = split('E',$x);
217 $xe = length($xm)+$xe-$scale;
221 &norm(&round('+0',"+0".substr($xm,$[+1,1),"+10"), $scale);
223 &norm(&round(substr($xm,$[,$xe),
224 "+0".substr($xm,$[+$xe,1),"+10"), $scale);
230 # compare 2 values returns one of undef, <0, =0, >0
231 # returns undef if either or both input value are not numbers
232 sub fcmp #(fnum_str, fnum_str) return cond_code
234 local($x, $y) = (fnorm($_[$[]),fnorm($_[$[+1]));
235 if ($x eq "NaN" || $y eq "NaN") {
240 ( local($xm,$xe,$ym,$ye) = split('E', $x."E$y"),
241 (($xe <=> $ye) * (substr($x,$[,1).'1')
242 || Math::BigInt::cmp($xm,$ym))
247 # square root by Newtons method.
248 sub fsqrt { #(fnum_str[, scale]) return fnum_str
249 local($x, $scale) = (fnorm($_[$[]), $_[$[+1]);
250 if ($x eq 'NaN' || $x =~ /^-/) {
252 } elsif ($x eq '+0E+0') {
255 local($xm, $xe) = split('E',$x);
256 $scale = $div_scale if (!$scale);
257 $scale = length($xm)-1 if ($scale < length($xm)-1);
258 local($gs, $guess) = (1, sprintf("1E%+d", (length($xm)+$xe-1)/2));
259 while ($gs < 2*$scale) {
260 $guess = fmul(fadd($guess,fdiv($x,$guess,$gs*2)),".5");
263 new Math::BigFloat &fround($guess, $scale);
272 Math::BigFloat - Arbitrary length float math package
277 $f = Math::BigFloat->new($string);
279 $f->fadd(NSTR) return NSTR addition
280 $f->fsub(NSTR) return NSTR subtraction
281 $f->fmul(NSTR) return NSTR multiplication
282 $f->fdiv(NSTR[,SCALE]) returns NSTR division to SCALE places
283 $f->fneg() return NSTR negation
284 $f->fabs() return NSTR absolute value
285 $f->fcmp(NSTR) return CODE compare undef,<0,=0,>0
286 $f->fround(SCALE) return NSTR round to SCALE digits
287 $f->ffround(SCALE) return NSTR round at SCALEth place
288 $f->fnorm() return (NSTR) normalize
289 $f->fsqrt([SCALE]) return NSTR sqrt to SCALE places
293 All basic math operations are overloaded if you declare your big
296 $float = new Math::BigFloat "2.123123123123123123123123123123123";
302 canonical strings have the form /[+-]\d+E[+-]\d+/ . Input values can
303 have inbedded whitespace.
305 =item Error returns 'NaN'
307 An input parameter was "Not a Number" or divide by zero or sqrt of
310 =item Division is computed to
312 C<max($div_scale,length(dividend)+length(divisor))> digits by default.
313 Also used for default sqrt scale.
319 The current version of this module is a preliminary version of the
320 real thing that is currently (as of perl5.002) under development.