1 package Math::BigFloat;
5 use Exporter; # just for use to be happy
7 $VERSION = '0.01'; # never had version before
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 'neg' => sub {new Math::BigFloat &fneg},
20 'abs' => sub {new Math::BigFloat &fabs},
21 'int' => sub {new Math::BigInt &f2int},
25 0+ numify) # Order of arguments unsignificant
30 my ($foo) = fnorm(shift);
34 sub numify { 0 + "${$_[0]}" } # Not needed, additional overhead
35 # comparing to direct compilation based on
40 my $minus = ($n =~ s/^([+-])// && $1 eq '-');
50 } elsif (abs($e) < $ln) {
51 substr($n, $ln + $e, 0) = '.';
53 $n = '.' . ("0" x (abs($e) - $ln)) . $n;
57 # 1 while $n =~ s/(.*\d)(\d\d\d)/$1,$2/;
65 die "unknown import: @_" unless @_ == 1 and $_[0] eq ':constant';
66 overload::constant float => sub {Math::BigFloat->new(shift)};
71 # Rounding modes one of 'even', 'odd', '+inf', '-inf', 'zero' or 'trunc'.
75 sub fadd; sub fsub; sub fmul; sub fdiv;
76 sub fneg; sub fabs; sub fcmp;
77 sub fround; sub ffround;
80 # Convert a number to canonical string form.
81 # Takes something that looks like a number and converts it to
82 # the form /^[+-]\d+E[+-]\d+$/.
83 sub fnorm { #(string) return fnum_str
85 s/\s+//g; # strip white space
86 no warnings; # $4 and $5 below might legitimately be undefined
87 if (/^([+-]?)(\d*)(\.(\d*))?([Ee]([+-]?\d+))?$/ && "$2$4" ne '') {
88 &norm(($1 ? "$1$2$4" : "+$2$4"),(($4 ne '') ? $6-length($4) : $6));
94 # normalize number -- for internal use
95 sub norm { #(mantissa, exponent) return fnum_str
97 $exp = 0 unless defined $exp;
101 s/^([+-])0+/$1/; # strip leading zeros
102 if (length($_) == 1) {
105 $exp += length($1) if (s/(0+)$//); # strip trailing zeros
106 sprintf("%sE%+ld", $_, $exp);
112 sub fneg { #(fnum_str) return fnum_str
113 local($_) = fnorm($_[$[]);
114 vec($_,0,8) ^= ord('+') ^ ord('-') unless $_ eq '+0E+0'; # flip sign
120 sub fabs { #(fnum_str) return fnum_str
121 local($_) = fnorm($_[$[]);
127 sub fmul { #(fnum_str, fnum_str) return fnum_str
128 local($x,$y) = (fnorm($_[$[]),fnorm($_[$[+1]));
129 if ($x eq 'NaN' || $y eq 'NaN') {
132 local($xm,$xe) = split('E',$x);
133 local($ym,$ye) = split('E',$y);
134 &norm(Math::BigInt::bmul($xm,$ym),$xe+$ye);
139 sub fadd { #(fnum_str, fnum_str) return fnum_str
140 local($x,$y) = (fnorm($_[$[]),fnorm($_[$[+1]));
141 if ($x eq 'NaN' || $y eq 'NaN') {
144 local($xm,$xe) = split('E',$x);
145 local($ym,$ye) = split('E',$y);
146 ($xm,$xe,$ym,$ye) = ($ym,$ye,$xm,$xe) if ($xe < $ye);
147 &norm(Math::BigInt::badd($ym,$xm.('0' x ($xe-$ye))),$ye);
152 sub fsub { #(fnum_str, fnum_str) return fnum_str
153 fadd($_[$[],fneg($_[$[+1]));
157 # args are dividend, divisor, scale (optional)
158 # result has at most max(scale, length(dividend), length(divisor)) digits
159 sub fdiv #(fnum_str, fnum_str[,scale]) return fnum_str
161 local($x,$y,$scale) = (fnorm($_[$[]),fnorm($_[$[+1]),$_[$[+2]);
162 if ($x eq 'NaN' || $y eq 'NaN' || $y eq '+0E+0') {
165 local($xm,$xe) = split('E',$x);
166 local($ym,$ye) = split('E',$y);
167 $scale = $div_scale if (!$scale);
168 $scale = length($xm)-1 if (length($xm)-1 > $scale);
169 $scale = length($ym)-1 if (length($ym)-1 > $scale);
170 $scale = $scale + length($ym) - length($xm);
171 &norm(&round(Math::BigInt::bdiv($xm.('0' x $scale),$ym),
172 Math::BigInt::babs($ym)),
177 # round int $q based on fraction $r/$base using $rnd_mode
178 sub round { #(int_str, int_str, int_str) return int_str
179 local($q,$r,$base) = @_;
180 if ($q eq 'NaN' || $r eq 'NaN') {
182 } elsif ($rnd_mode eq 'trunc') {
185 local($cmp) = Math::BigInt::bcmp(Math::BigInt::bmul($r,'+2'),$base);
188 ($rnd_mode eq 'zero' ) ||
189 ($rnd_mode eq '-inf' && (substr($q,$[,1) eq '+')) ||
190 ($rnd_mode eq '+inf' && (substr($q,$[,1) eq '-')) ||
191 ($rnd_mode eq 'even' && $q =~ /[13579]$/ ) ||
192 ($rnd_mode eq 'odd' && $q =~ /[24680]$/ ) )
197 Math::BigInt::badd($q, ((substr($q,$[,1) eq '-') ? '-1' : '+1'));
203 # round the mantissa of $x to $scale digits
204 sub fround { #(fnum_str, scale) return fnum_str
205 local($x,$scale) = (fnorm($_[$[]),$_[$[+1]);
206 if ($x eq 'NaN' || $scale <= 0) {
209 local($xm,$xe) = split('E',$x);
210 if (length($xm)-1 <= $scale) {
213 &norm(&round(substr($xm,$[,$scale+1),
214 "+0".substr($xm,$[+$scale+1,1),"+10"),
215 $xe+length($xm)-$scale-1);
220 # round $x at the 10 to the $scale digit place
221 sub ffround { #(fnum_str, scale) return fnum_str
222 local($x,$scale) = (fnorm($_[$[]),$_[$[+1]);
226 local($xm,$xe) = split('E',$x);
230 $xe = length($xm)+$xe-$scale;
234 # The first substr preserves the sign, passing a non-
235 # normalized "-0" to &round when rounding -0.006 (for
236 # example), purely so &round won't lose the sign.
237 &norm(&round(substr($xm,$[,1).'0',
238 "+0".substr($xm,$[+1,1),"+10"), $scale);
240 &norm(&round(substr($xm,$[,$xe),
241 "+0".substr($xm,$[+$xe,1),"+10"), $scale);
247 # Calculate the integer part of $x
248 sub f2int { #(fnum_str) return inum_str
249 local($x) = ${$_[$[]};
251 die "Attempt to take int(NaN)";
253 local($xm,$xe) = split('E',$x);
257 $xe = length($xm)+$xe;
267 # compare 2 values returns one of undef, <0, =0, >0
268 # returns undef if either or both input value are not numbers
269 sub fcmp #(fnum_str, fnum_str) return cond_code
271 local($x, $y) = (fnorm($_[$[]),fnorm($_[$[+1]));
272 if ($x eq "NaN" || $y eq "NaN") {
275 local($xm,$xe,$ym,$ye) = split('E', $x."E$y");
276 if ($xm eq '+0' || $ym eq '+0') {
279 if ( $xe < $ye ) # adjust the exponents to be equal
281 $ym .= '0' x ($ye - $xe);
284 elsif ( $ye < $xe ) # same here
286 $xm .= '0' x ($xe - $ye);
289 return Math::BigInt::cmp($xm,$ym);
293 # square root by Newtons method.
294 sub fsqrt { #(fnum_str[, scale]) return fnum_str
295 local($x, $scale) = (fnorm($_[$[]), $_[$[+1]);
296 if ($x eq 'NaN' || $x =~ /^-/) {
298 } elsif ($x eq '+0E+0') {
301 local($xm, $xe) = split('E',$x);
302 $scale = $div_scale if (!$scale);
303 $scale = length($xm)-1 if ($scale < length($xm)-1);
304 local($gs, $guess) = (1, sprintf("1E%+d", (length($xm)+$xe-1)/2));
305 while ($gs < 2*$scale) {
306 $guess = fmul(fadd($guess,fdiv($x,$guess,$gs*2)),".5");
309 new Math::BigFloat &fround($guess, $scale);
318 Math::BigFloat - Arbitrary length float math package
323 $f = Math::BigFloat->new($string);
325 $f->fadd(NSTR) return NSTR addition
326 $f->fsub(NSTR) return NSTR subtraction
327 $f->fmul(NSTR) return NSTR multiplication
328 $f->fdiv(NSTR[,SCALE]) returns NSTR division to SCALE places
329 $f->fneg() return NSTR negation
330 $f->fabs() return NSTR absolute value
331 $f->fcmp(NSTR) return CODE compare undef,<0,=0,>0
332 $f->fround(SCALE) return NSTR round to SCALE digits
333 $f->ffround(SCALE) return NSTR round at SCALEth place
334 $f->fnorm() return (NSTR) normalize
335 $f->fsqrt([SCALE]) return NSTR sqrt to SCALE places
339 All basic math operations are overloaded if you declare your big
342 $float = new Math::BigFloat "2.123123123123123123123123123123123";
348 canonical strings have the form /[+-]\d+E[+-]\d+/ . Input values can
349 have embedded whitespace.
351 =item Error returns 'NaN'
353 An input parameter was "Not a Number" or divide by zero or sqrt of
356 =item Division is computed to
358 C<max($Math::BigFloat::div_scale,length(dividend)+length(divisor))>
360 Also used for default sqrt scale.
362 =item Rounding is performed
364 according to the value of
365 C<$Math::BigFloat::rnd_mode>:
367 trunc truncate the value
369 +inf round towards +infinity (round up)
370 -inf round towards -infinity (round down)
371 even round to the nearest, .5 to the even digit
372 odd round to the nearest, .5 to the odd digit
374 The default is C<even> rounding.
380 The current version of this module is a preliminary version of the
381 real thing that is currently (as of perl5.002) under development.
383 The printf subroutine does not use the value of
384 C<$Math::BigFloat::rnd_mode> when rounding values for printing.
385 Consequently, the way to print rounded values is
386 to specify the number of digits both as an
387 argument to C<ffround> and in the C<%f> printf string,
390 printf "%.3f\n", $bigfloat->ffround(-3);