1 package Math::BigFloat;
5 use Exporter; # just for use to be happy
10 '+' => sub {new Math::BigFloat &fadd},
11 '-' => sub {new Math::BigFloat
12 $_[2]? fsub($_[1],${$_[0]}) : fsub(${$_[0]},$_[1])},
13 '<=>' => sub {$_[2]? fcmp($_[1],${$_[0]}) : fcmp(${$_[0]},$_[1])},
14 'cmp' => sub {$_[2]? ($_[1] cmp ${$_[0]}) : (${$_[0]} cmp $_[1])},
15 '*' => sub {new Math::BigFloat &fmul},
16 '/' => sub {new Math::BigFloat
17 $_[2]? scalar fdiv($_[1],${$_[0]}) :
18 scalar fdiv(${$_[0]},$_[1])},
19 '%' => sub {new Math::BigFloat
20 $_[2]? scalar fmod($_[1],${$_[0]}) :
21 scalar fmod(${$_[0]},$_[1])},
22 'neg' => sub {new Math::BigFloat &fneg},
23 'abs' => sub {new Math::BigFloat &fabs},
24 'int' => sub {new Math::BigInt &f2int},
28 0+ numify) # Order of arguments unsignificant
33 my ($foo) = fnorm(shift);
37 sub numify { 0 + "${$_[0]}" } # Not needed, additional overhead
38 # comparing to direct compilation based on
43 my $minus = ($n =~ s/^([+-])// && $1 eq '-');
55 } elsif (abs($e) < $ln) {
56 substr($n, $ln + $e, 0) = '.';
58 $n = '.' . ("0" x (abs($e) - $ln)) . $n;
63 # 1 while $n =~ s/(.*\d)(\d\d\d)/$1,$2/;
71 if (@_ == 1 && $_[0] ne ':constant') {
73 if ($VERSION < $_[0]) {
74 die __PACKAGE__.": $_[0] required--this is only version $VERSION";
77 die __PACKAGE__.": unknown import: $_[0]";
80 overload::constant float => sub {Math::BigFloat->new(shift)};
85 # Rounding modes one of 'even', 'odd', '+inf', '-inf', 'zero' or 'trunc'.
89 sub fadd; sub fsub; sub fmul; sub fdiv;
90 sub fneg; sub fabs; sub fcmp;
91 sub fround; sub ffround;
94 # Convert a number to canonical string form.
95 # Takes something that looks like a number and converts it to
96 # the form /^[+-]\d+E[+-]\d+$/.
97 sub fnorm { #(string) return fnum_str
99 s/\s+//g; # strip white space
100 no warnings; # $4 and $5 below might legitimately be undefined
101 if (/^([+-]?)(\d*)(\.(\d*))?([Ee]([+-]?\d+))?$/ && "$2$4" ne '') {
102 &norm(($1 ? "$1$2$4" : "+$2$4"),(($4 ne '') ? $6-length($4) : $6));
108 # normalize number -- for internal use
109 sub norm { #(mantissa, exponent) return fnum_str
110 local($_, $exp) = @_;
111 $exp = 0 unless defined $exp;
115 s/^([+-])0+/$1/; # strip leading zeros
116 if (length($_) == 1) {
119 $exp += length($1) if (s/(0+)$//); # strip trailing zeros
120 sprintf("%sE%+ld", $_, $exp);
126 sub fneg { #(fnum_str) return fnum_str
127 local($_) = fnorm($_[$[]);
128 vec($_,0,8) ^= ord('+') ^ ord('-') unless $_ eq '+0E+0'; # flip sign
134 sub fabs { #(fnum_str) return fnum_str
135 local($_) = fnorm($_[$[]);
141 sub fmul { #(fnum_str, fnum_str) return fnum_str
142 local($x,$y) = (fnorm($_[$[]),fnorm($_[$[+1]));
143 if ($x eq 'NaN' || $y eq 'NaN') {
146 local($xm,$xe) = split('E',$x);
147 local($ym,$ye) = split('E',$y);
148 &norm(Math::BigInt::bmul($xm,$ym),$xe+$ye);
153 sub fadd { #(fnum_str, fnum_str) return fnum_str
154 local($x,$y) = (fnorm($_[$[]),fnorm($_[$[+1]));
155 if ($x eq 'NaN' || $y eq 'NaN') {
158 local($xm,$xe) = split('E',$x);
159 local($ym,$ye) = split('E',$y);
160 ($xm,$xe,$ym,$ye) = ($ym,$ye,$xm,$xe) if ($xe < $ye);
161 &norm(Math::BigInt::badd($ym,$xm.('0' x ($xe-$ye))),$ye);
166 sub fsub { #(fnum_str, fnum_str) return fnum_str
167 fadd($_[$[],fneg($_[$[+1]));
171 # args are dividend, divisor, scale (optional)
172 # result has at most max(scale, length(dividend), length(divisor)) digits
173 sub fdiv #(fnum_str, fnum_str[,scale]) return fnum_str
175 local($x,$y,$scale) = (fnorm($_[$[]),fnorm($_[$[+1]),$_[$[+2]);
176 if ($x eq 'NaN' || $y eq 'NaN' || $y eq '+0E+0') {
179 local($xm,$xe) = split('E',$x);
180 local($ym,$ye) = split('E',$y);
181 $scale = $div_scale if (!$scale);
182 $scale = length($xm)-1 if (length($xm)-1 > $scale);
183 $scale = length($ym)-1 if (length($ym)-1 > $scale);
184 $scale = $scale + length($ym) - length($xm);
185 &norm(&round(Math::BigInt::bdiv($xm.('0' x $scale),$ym),
186 Math::BigInt::babs($ym)),
192 # args are dividend, divisor
193 sub fmod #(fnum_str, fnum_str) return fnum_str
195 local($x,$y) = (fnorm($_[$[]),fnorm($_[$[+1]));
196 if ($x eq 'NaN' || $y eq 'NaN' || $y eq '+0E+0') {
199 local($xm,$xe) = split('E',$x);
200 local($ym,$ye) = split('E',$y);
203 $ym .= ('0' x ($ye-$xe));
207 $xm .= ('0' x ($xe-$ye));
209 &norm(Math::BigInt::bmod($xm,$ym));
212 # round int $q based on fraction $r/$base using $rnd_mode
213 sub round { #(int_str, int_str, int_str) return int_str
214 local($q,$r,$base) = @_;
215 if ($q eq 'NaN' || $r eq 'NaN') {
217 } elsif ($rnd_mode eq 'trunc') {
220 local($cmp) = Math::BigInt::bcmp(Math::BigInt::bmul($r,'+2'),$base);
223 ($rnd_mode eq 'zero' ) ||
224 ($rnd_mode eq '-inf' && (substr($q,$[,1) eq '+')) ||
225 ($rnd_mode eq '+inf' && (substr($q,$[,1) eq '-')) ||
226 ($rnd_mode eq 'even' && $q =~ /[24680]$/ ) ||
227 ($rnd_mode eq 'odd' && $q =~ /[13579]$/ ) )
232 Math::BigInt::badd($q, ((substr($q,$[,1) eq '-') ? '-1' : '+1'));
238 # round the mantissa of $x to $scale digits
239 sub fround { #(fnum_str, scale) return fnum_str
240 local($x,$scale) = (fnorm($_[$[]),$_[$[+1]);
241 if ($x eq 'NaN' || $scale <= 0) {
244 local($xm,$xe) = split('E',$x);
245 if (length($xm)-1 <= $scale) {
248 &norm(&round(substr($xm,$[,$scale+1),
249 "+0".substr($xm,$[+$scale+1),"+1"."0" x length(substr($xm,$[+$scale+1))),
250 $xe+length($xm)-$scale-1);
255 # round $x at the 10 to the $scale digit place
256 sub ffround { #(fnum_str, scale) return fnum_str
257 local($x,$scale) = (fnorm($_[$[]),$_[$[+1]);
261 local($xm,$xe) = split('E',$x);
265 $xe = length($xm)+$xe-$scale;
269 # The first substr preserves the sign, passing a non-
270 # normalized "-0" to &round when rounding -0.006 (for
271 # example), purely so &round won't lose the sign.
272 &norm(&round(substr($xm,$[,1).'0',
273 "+0".substr($xm,$[+1),
274 "+1"."0" x length(substr($xm,$[+1))), $scale);
276 &norm(&round(substr($xm,$[,$xe),
277 "+0".substr($xm,$[+$xe),
278 "+1"."0" x length(substr($xm,$[+$xe))), $scale);
284 # Calculate the integer part of $x
285 sub f2int { #(fnum_str) return inum_str
286 local($x) = ${$_[$[]};
288 die "Attempt to take int(NaN)";
290 local($xm,$xe) = split('E',$x);
294 $xe = length($xm)+$xe;
304 # compare 2 values returns one of undef, <0, =0, >0
305 # returns undef if either or both input value are not numbers
306 sub fcmp #(fnum_str, fnum_str) return cond_code
308 local($x, $y) = (fnorm($_[$[]),fnorm($_[$[+1]));
309 if ($x eq "NaN" || $y eq "NaN") {
312 local($xm,$xe,$ym,$ye) = split('E', $x."E$y");
313 if ($xm eq '+0' || $ym eq '+0') {
316 if ( $xe < $ye ) # adjust the exponents to be equal
318 $ym .= '0' x ($ye - $xe);
321 elsif ( $ye < $xe ) # same here
323 $xm .= '0' x ($xe - $ye);
326 return Math::BigInt::cmp($xm,$ym);
330 # square root by Newtons method.
331 sub fsqrt { #(fnum_str[, scale]) return fnum_str
332 local($x, $scale) = (fnorm($_[$[]), $_[$[+1]);
333 if ($x eq 'NaN' || $x =~ /^-/) {
335 } elsif ($x eq '+0E+0') {
338 local($xm, $xe) = split('E',$x);
339 $scale = $div_scale if (!$scale);
340 $scale = length($xm)-1 if ($scale < length($xm)-1);
341 local($gs, $guess) = (1, sprintf("1E%+d", (length($xm)+$xe-1)/2));
342 while ($gs < 2*$scale) {
343 $guess = fmul(fadd($guess,fdiv($x,$guess,$gs*2)),".5");
346 new Math::BigFloat &fround($guess, $scale);
355 Math::BigFloat - Arbitrary length float math package
360 $f = Math::BigFloat->new($string);
362 $f->fadd(NSTR) return NSTR addition
363 $f->fsub(NSTR) return NSTR subtraction
364 $f->fmul(NSTR) return NSTR multiplication
365 $f->fdiv(NSTR[,SCALE]) returns NSTR division to SCALE places
366 $f->fmod(NSTR) returns NSTR modular remainder
367 $f->fneg() return NSTR negation
368 $f->fabs() return NSTR absolute value
369 $f->fcmp(NSTR) return CODE compare undef,<0,=0,>0
370 $f->fround(SCALE) return NSTR round to SCALE digits
371 $f->ffround(SCALE) return NSTR round at SCALEth place
372 $f->fnorm() return (NSTR) normalize
373 $f->fsqrt([SCALE]) return NSTR sqrt to SCALE places
377 All basic math operations are overloaded if you declare your big
380 $float = new Math::BigFloat "2.123123123123123123123123123123123";
386 canonical strings have the form /[+-]\d+E[+-]\d+/ . Input values can
387 have embedded whitespace.
389 =item Error returns 'NaN'
391 An input parameter was "Not a Number" or divide by zero or sqrt of
394 =item Division is computed to
396 C<max($Math::BigFloat::div_scale,length(dividend)+length(divisor))>
398 Also used for default sqrt scale.
400 =item Rounding is performed
402 according to the value of
403 C<$Math::BigFloat::rnd_mode>:
405 trunc truncate the value
407 +inf round towards +infinity (round up)
408 -inf round towards -infinity (round down)
409 even round to the nearest, .5 to the even digit
410 odd round to the nearest, .5 to the odd digit
412 The default is C<even> rounding.
418 The current version of this module is a preliminary version of the
419 real thing that is currently (as of perl5.002) under development.
421 The printf subroutine does not use the value of
422 C<$Math::BigFloat::rnd_mode> when rounding values for printing.
423 Consequently, the way to print rounded values is
424 to specify the number of digits both as an
425 argument to C<ffround> and in the C<%f> printf string,
428 printf "%.3f\n", $bigfloat->ffround(-3);
433 Patches by John Peacock Apr 2001