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
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/;
64 # Rounding modes one of 'even', 'odd', '+inf', '-inf', 'zero' or 'trunc'.
68 sub fadd; sub fsub; sub fmul; sub fdiv;
69 sub fneg; sub fabs; sub fcmp;
70 sub fround; sub ffround;
73 # Convert a number to canonical string form.
74 # Takes something that looks like a number and converts it to
75 # the form /^[+-]\d+E[+-]\d+$/.
76 sub fnorm { #(string) return fnum_str
78 s/\s+//g; # strip white space
79 if (/^([+-]?)(\d*)(\.(\d*))?([Ee]([+-]?\d+))?$/ && "$2$4" ne '') {
80 &norm(($1 ? "$1$2$4" : "+$2$4"),(($4 ne '') ? $6-length($4) : $6));
86 # normalize number -- for internal use
87 sub norm { #(mantissa, exponent) return fnum_str
92 s/^([+-])0+/$1/; # strip leading zeros
93 if (length($_) == 1) {
96 $exp += length($1) if (s/(0+)$//); # strip trailing zeros
97 sprintf("%sE%+ld", $_, $exp);
103 sub fneg { #(fnum_str) return fnum_str
104 local($_) = fnorm($_[$[]);
105 vec($_,0,8) ^= ord('+') ^ ord('-') unless $_ eq '+0E+0'; # flip sign
111 sub fabs { #(fnum_str) return fnum_str
112 local($_) = fnorm($_[$[]);
118 sub fmul { #(fnum_str, fnum_str) return fnum_str
119 local($x,$y) = (fnorm($_[$[]),fnorm($_[$[+1]));
120 if ($x eq 'NaN' || $y eq 'NaN') {
123 local($xm,$xe) = split('E',$x);
124 local($ym,$ye) = split('E',$y);
125 &norm(Math::BigInt::bmul($xm,$ym),$xe+$ye);
130 sub fadd { #(fnum_str, fnum_str) return fnum_str
131 local($x,$y) = (fnorm($_[$[]),fnorm($_[$[+1]));
132 if ($x eq 'NaN' || $y eq 'NaN') {
135 local($xm,$xe) = split('E',$x);
136 local($ym,$ye) = split('E',$y);
137 ($xm,$xe,$ym,$ye) = ($ym,$ye,$xm,$xe) if ($xe < $ye);
138 &norm(Math::BigInt::badd($ym,$xm.('0' x ($xe-$ye))),$ye);
143 sub fsub { #(fnum_str, fnum_str) return fnum_str
144 fadd($_[$[],fneg($_[$[+1]));
148 # args are dividend, divisor, scale (optional)
149 # result has at most max(scale, length(dividend), length(divisor)) digits
150 sub fdiv #(fnum_str, fnum_str[,scale]) return fnum_str
152 local($x,$y,$scale) = (fnorm($_[$[]),fnorm($_[$[+1]),$_[$[+2]);
153 if ($x eq 'NaN' || $y eq 'NaN' || $y eq '+0E+0') {
156 local($xm,$xe) = split('E',$x);
157 local($ym,$ye) = split('E',$y);
158 $scale = $div_scale if (!$scale);
159 $scale = length($xm)-1 if (length($xm)-1 > $scale);
160 $scale = length($ym)-1 if (length($ym)-1 > $scale);
161 $scale = $scale + length($ym) - length($xm);
162 &norm(&round(Math::BigInt::bdiv($xm.('0' x $scale),$ym),$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 &norm(&round('+0',"+0".substr($xm,$[+1,1),"+10"), $scale);
224 &norm(&round(substr($xm,$[,$xe),
225 "+0".substr($xm,$[+$xe,1),"+10"), $scale);
231 # compare 2 values returns one of undef, <0, =0, >0
232 # returns undef if either or both input value are not numbers
233 sub fcmp #(fnum_str, fnum_str) return cond_code
235 local($x, $y) = (fnorm($_[$[]),fnorm($_[$[+1]));
236 if ($x eq "NaN" || $y eq "NaN") {
241 ( local($xm,$xe,$ym,$ye) = split('E', $x."E$y"),
242 (($xe <=> $ye) * (substr($x,$[,1).'1')
243 || Math::BigInt::cmp($xm,$ym))
248 # square root by Newtons method.
249 sub fsqrt { #(fnum_str[, scale]) return fnum_str
250 local($x, $scale) = (fnorm($_[$[]), $_[$[+1]);
251 if ($x eq 'NaN' || $x =~ /^-/) {
253 } elsif ($x eq '+0E+0') {
256 local($xm, $xe) = split('E',$x);
257 $scale = $div_scale if (!$scale);
258 $scale = length($xm)-1 if ($scale < length($xm)-1);
259 local($gs, $guess) = (1, sprintf("1E%+d", (length($xm)+$xe-1)/2));
260 while ($gs < 2*$scale) {
261 $guess = fmul(fadd($guess,fdiv($x,$guess,$gs*2)),".5");
264 new Math::BigFloat &fround($guess, $scale);
273 Math::BigFloat - Arbitrary length float math package
278 $f = Math::BigFloat->new($string);
280 $f->fadd(NSTR) return NSTR addition
281 $f->fsub(NSTR) return NSTR subtraction
282 $f->fmul(NSTR) return NSTR multiplication
283 $f->fdiv(NSTR[,SCALE]) returns NSTR division to SCALE places
284 $f->fneg() return NSTR negation
285 $f->fabs() return NSTR absolute value
286 $f->fcmp(NSTR) return CODE compare undef,<0,=0,>0
287 $f->fround(SCALE) return NSTR round to SCALE digits
288 $f->ffround(SCALE) return NSTR round at SCALEth place
289 $f->fnorm() return (NSTR) normalize
290 $f->fsqrt([SCALE]) return NSTR sqrt to SCALE places
294 All basic math operations are overloaded if you declare your big
297 $float = new Math::BigFloat "2.123123123123123123123123123123123";
303 canonical strings have the form /[+-]\d+E[+-]\d+/ . Input values can
304 have embedded whitespace.
306 =item Error returns 'NaN'
308 An input parameter was "Not a Number" or divide by zero or sqrt of
311 =item Division is computed to
313 C<max($div_scale,length(dividend)+length(divisor))> digits by default.
314 Also used for default sqrt scale.
320 The current version of this module is a preliminary version of the
321 real thing that is currently (as of perl5.002) under development.