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 {$_[2]? fcmp($_[1],${$_[0]}) : fcmp(${$_[0]},$_[1])},
13 'cmp' => sub {$_[2]? ($_[1] cmp ${$_[0]}) : (${$_[0]} cmp $_[1])},
14 '*' => sub {new Math::BigFloat &fmul},
15 '/' => sub {new Math::BigFloat
16 $_[2]? scalar fdiv($_[1],${$_[0]}) :
17 scalar fdiv(${$_[0]},$_[1])},
18 'neg' => sub {new Math::BigFloat &fneg},
19 'abs' => sub {new Math::BigFloat &fabs},
23 0+ numify) # Order of arguments unsignificant
28 my ($foo) = fnorm(shift);
32 sub numify { 0 + "${$_[0]}" } # Not needed, additional overhead
33 # comparing to direct compilation based on
38 my $minus = ($n =~ s/^([+-])// && $1 eq '-');
48 } elsif (abs($e) < $ln) {
49 substr($n, $ln + $e, 0) = '.';
51 $n = '.' . ("0" x (abs($e) - $ln)) . $n;
55 # 1 while $n =~ s/(.*\d)(\d\d\d)/$1,$2/;
62 # Rounding modes one of 'even', 'odd', '+inf', '-inf', 'zero' or 'trunc'.
66 sub fadd; sub fsub; sub fmul; sub fdiv;
67 sub fneg; sub fabs; sub fcmp;
68 sub fround; sub ffround;
71 # Convert a number to canonical string form.
72 # Takes something that looks like a number and converts it to
73 # the form /^[+-]\d+E[+-]\d+$/.
74 sub fnorm { #(string) return fnum_str
76 s/\s+//g; # strip white space
77 no warnings; # $4 and $5 below might legitimately be undefined
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),
162 Math::BigInt::babs($ym)),
167 # round int $q based on fraction $r/$base using $rnd_mode
168 sub round { #(int_str, int_str, int_str) return int_str
169 local($q,$r,$base) = @_;
170 if ($q eq 'NaN' || $r eq 'NaN') {
172 } elsif ($rnd_mode eq 'trunc') {
175 local($cmp) = Math::BigInt::bcmp(Math::BigInt::bmul($r,'+2'),$base);
178 ( $rnd_mode eq 'zero' ||
179 ($rnd_mode eq '-inf' && (substr($q,$[,1) eq '+')) ||
180 ($rnd_mode eq '+inf' && (substr($q,$[,1) eq '-')) ||
181 ($rnd_mode eq 'even' && $q =~ /[24680]$/) ||
182 ($rnd_mode eq 'odd' && $q =~ /[13579]$/) )) ) {
185 Math::BigInt::badd($q, ((substr($q,$[,1) eq '-') ? '-1' : '+1'));
191 # round the mantissa of $x to $scale digits
192 sub fround { #(fnum_str, scale) return fnum_str
193 local($x,$scale) = (fnorm($_[$[]),$_[$[+1]);
194 if ($x eq 'NaN' || $scale <= 0) {
197 local($xm,$xe) = split('E',$x);
198 if (length($xm)-1 <= $scale) {
201 &norm(&round(substr($xm,$[,$scale+1),
202 "+0".substr($xm,$[+$scale+1,1),"+10"),
203 $xe+length($xm)-$scale-1);
208 # round $x at the 10 to the $scale digit place
209 sub ffround { #(fnum_str, scale) return fnum_str
210 local($x,$scale) = (fnorm($_[$[]),$_[$[+1]);
214 local($xm,$xe) = split('E',$x);
218 $xe = length($xm)+$xe-$scale;
222 # The first substr preserves the sign, passing a non-
223 # normalized "-0" to &round when rounding -0.006 (for
224 # example), purely so &round won't lose the sign.
225 &norm(&round(substr($xm,$[,1).'0',
226 "+0".substr($xm,$[+1,1),"+10"), $scale);
228 &norm(&round(substr($xm,$[,$xe),
229 "+0".substr($xm,$[+$xe,1),"+10"), $scale);
235 # compare 2 values returns one of undef, <0, =0, >0
236 # returns undef if either or both input value are not numbers
237 sub fcmp #(fnum_str, fnum_str) return cond_code
239 local($x, $y) = (fnorm($_[$[]),fnorm($_[$[+1]));
240 if ($x eq "NaN" || $y eq "NaN") {
243 local($xm,$xe,$ym,$ye) = split('E', $x."E$y");
244 if ($xm eq '+0' || $ym eq '+0') {
248 || ($xe <=> $ye) * (substr($x,$[,1).'1')
249 || Math::BigInt::cmp($xm,$ym);
253 # square root by Newtons method.
254 sub fsqrt { #(fnum_str[, scale]) return fnum_str
255 local($x, $scale) = (fnorm($_[$[]), $_[$[+1]);
256 if ($x eq 'NaN' || $x =~ /^-/) {
258 } elsif ($x eq '+0E+0') {
261 local($xm, $xe) = split('E',$x);
262 $scale = $div_scale if (!$scale);
263 $scale = length($xm)-1 if ($scale < length($xm)-1);
264 local($gs, $guess) = (1, sprintf("1E%+d", (length($xm)+$xe-1)/2));
265 while ($gs < 2*$scale) {
266 $guess = fmul(fadd($guess,fdiv($x,$guess,$gs*2)),".5");
269 new Math::BigFloat &fround($guess, $scale);
278 Math::BigFloat - Arbitrary length float math package
283 $f = Math::BigFloat->new($string);
285 $f->fadd(NSTR) return NSTR addition
286 $f->fsub(NSTR) return NSTR subtraction
287 $f->fmul(NSTR) return NSTR multiplication
288 $f->fdiv(NSTR[,SCALE]) returns NSTR division to SCALE places
289 $f->fneg() return NSTR negation
290 $f->fabs() return NSTR absolute value
291 $f->fcmp(NSTR) return CODE compare undef,<0,=0,>0
292 $f->fround(SCALE) return NSTR round to SCALE digits
293 $f->ffround(SCALE) return NSTR round at SCALEth place
294 $f->fnorm() return (NSTR) normalize
295 $f->fsqrt([SCALE]) return NSTR sqrt to SCALE places
299 All basic math operations are overloaded if you declare your big
302 $float = new Math::BigFloat "2.123123123123123123123123123123123";
308 canonical strings have the form /[+-]\d+E[+-]\d+/ . Input values can
309 have embedded whitespace.
311 =item Error returns 'NaN'
313 An input parameter was "Not a Number" or divide by zero or sqrt of
316 =item Division is computed to
318 C<max($Math::BigFloat::div_scale,length(dividend)+length(divisor))>
320 Also used for default sqrt scale.
322 =item Rounding is performed
324 according to the value of
325 C<$Math::BigFloat::rnd_mode>:
327 trunc truncate the value
329 +inf round towards +infinity (round up)
330 -inf round towards -infinity (round down)
331 even round to the nearest, .5 to the even digit
332 odd round to the nearest, .5 to the odd digit
334 The default is C<even> rounding.
340 The current version of this module is a preliminary version of the
341 real thing that is currently (as of perl5.002) under development.
343 The printf subroutine does not use the value of
344 C<$Math::BigFloat::rnd_mode> when rounding values for printing.
345 Consequently, the way to print rounded values is
346 to specify the number of digits both as an
347 argument to C<ffround> and in the C<%f> printf string,
350 printf "%.3f\n", $bigfloat->ffround(-3);