fix bug when one of the operands is +0E+0 (from Ronald J Kimball
[p5sagit/p5-mst-13.2.git] / lib / Math / BigFloat.pm
1 package Math::BigFloat;
2
3 use Math::BigInt;
4
5 use Exporter;  # just for use to be happy
6 @ISA = (Exporter);
7
8 use overload
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},
20
21 qw(
22 ""      stringify
23 0+      numify)                 # Order of arguments unsignificant
24 ;
25
26 sub new {
27   my ($class) = shift;
28   my ($foo) = fnorm(shift);
29   bless \$foo, $class;
30 }
31
32 sub numify { 0 + "${$_[0]}" }   # Not needed, additional overhead
33                                 # comparing to direct compilation based on
34                                 # stringify
35 sub stringify {
36     my $n = ${$_[0]};
37
38     my $minus = ($n =~ s/^([+-])// && $1 eq '-');
39     $n =~ s/E//;
40
41     $n =~ s/([-+]\d+)$//;
42
43     my $e = $1;
44     my $ln = length($n);
45
46     if ($e > 0) {
47         $n .= "0" x $e . '.';
48     } elsif (abs($e) < $ln) {
49         substr($n, $ln + $e, 0) = '.';
50     } else {
51         $n = '.' . ("0" x (abs($e) - $ln)) . $n;
52     }
53     $n = "-$n" if $minus;
54
55     # 1 while $n =~ s/(.*\d)(\d\d\d)/$1,$2/;
56
57     return $n;
58 }
59
60 $div_scale = 40;
61
62 # Rounding modes one of 'even', 'odd', '+inf', '-inf', 'zero' or 'trunc'.
63
64 $rnd_mode = 'even';
65
66 sub fadd; sub fsub; sub fmul; sub fdiv;
67 sub fneg; sub fabs; sub fcmp;
68 sub fround; sub ffround;
69 sub fnorm; sub fsqrt;
70
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
75     local($_) = @_;
76     s/\s+//g;                               # strip white space
77     local $^W = 0;      # $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));
80     } else {
81         'NaN';
82     }
83 }
84
85 # normalize number -- for internal use
86 sub norm { #(mantissa, exponent) return fnum_str
87     local($_, $exp) = @_;
88     if ($_ eq 'NaN') {
89         'NaN';
90     } else {
91         s/^([+-])0+/$1/;                        # strip leading zeros
92         if (length($_) == 1) {
93             '+0E+0';
94         } else {
95             $exp += length($1) if (s/(0+)$//);  # strip trailing zeros
96             sprintf("%sE%+ld", $_, $exp);
97         }
98     }
99 }
100
101 # negation
102 sub fneg { #(fnum_str) return fnum_str
103     local($_) = fnorm($_[$[]);
104     vec($_,0,8) ^= ord('+') ^ ord('-') unless $_ eq '+0E+0'; # flip sign
105     s/^H/N/;
106     $_;
107 }
108
109 # absolute value
110 sub fabs { #(fnum_str) return fnum_str
111     local($_) = fnorm($_[$[]);
112     s/^-/+/;                                   # mash sign
113     $_;
114 }
115
116 # multiplication
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') {
120         'NaN';
121     } else {
122         local($xm,$xe) = split('E',$x);
123         local($ym,$ye) = split('E',$y);
124         &norm(Math::BigInt::bmul($xm,$ym),$xe+$ye);
125     }
126 }
127
128 # addition
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') {
132         'NaN';
133     } else {
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);
138     }
139 }
140
141 # subtraction
142 sub fsub { #(fnum_str, fnum_str) return fnum_str
143     fadd($_[$[],fneg($_[$[+1]));    
144 }
145
146 # division
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
150 {
151     local($x,$y,$scale) = (fnorm($_[$[]),fnorm($_[$[+1]),$_[$[+2]);
152     if ($x eq 'NaN' || $y eq 'NaN' || $y eq '+0E+0') {
153         'NaN';
154     } else {
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)),
163             $xe-$ye-$scale);
164     }
165 }
166
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') {
171         'NaN';
172     } elsif ($rnd_mode eq 'trunc') {
173         $q;                         # just truncate
174     } else {
175         local($cmp) = Math::BigInt::bcmp(Math::BigInt::bmul($r,'+2'),$base);
176         if ( $cmp < 0 ||
177                  ($cmp == 0 &&
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]$/)        )) ) {
183             $q;                     # round down
184         } else {
185             Math::BigInt::badd($q, ((substr($q,$[,1) eq '-') ? '-1' : '+1'));
186                                     # round up
187         }
188     }
189 }
190
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) {
195         $x;
196     } else {
197         local($xm,$xe) = split('E',$x);
198         if (length($xm)-1 <= $scale) {
199             $x;
200         } else {
201             &norm(&round(substr($xm,$[,$scale+1),
202                          "+0".substr($xm,$[+$scale+1,1),"+10"),
203                   $xe+length($xm)-$scale-1);
204         }
205     }
206 }
207
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]);
211     if ($x eq 'NaN') {
212         'NaN';
213     } else {
214         local($xm,$xe) = split('E',$x);
215         if ($xe >= $scale) {
216             $x;
217         } else {
218             $xe = length($xm)+$xe-$scale;
219             if ($xe < 1) {
220                 '+0E+0';
221             } elsif ($xe == 1) {
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);
227             } else {
228                 &norm(&round(substr($xm,$[,$xe),
229                       "+0".substr($xm,$[+$xe,1),"+10"), $scale);
230             }
231         }
232     }
233 }
234     
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
238 {
239     local($x, $y) = (fnorm($_[$[]),fnorm($_[$[+1]));
240     if ($x eq "NaN" || $y eq "NaN") {
241         undef;
242     } else {
243         local($xm,$xe,$ym,$ye) = split('E', $x."E$y");
244         if ($xm eq '+0' || $ym eq '+0') {
245             return $xm <=> $ym;
246         }
247         ord($y) <=> ord($x)
248         || ($xe <=> $ye) * (substr($x,$[,1).'1')
249         || Math::BigInt::cmp($xm,$ym);
250     }
251 }
252
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 =~ /^-/) {
257         'NaN';
258     } elsif ($x eq '+0E+0') {
259         '+0E+0';
260     } else {
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");
267             $gs *= 2;
268         }
269         new Math::BigFloat &fround($guess, $scale);
270     }
271 }
272
273 1;
274 __END__
275
276 =head1 NAME
277
278 Math::BigFloat - Arbitrary length float math package
279
280 =head1 SYNOPSIS
281
282   use Math::BigFloat;
283   $f = Math::BigFloat->new($string);
284
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
296
297 =head1 DESCRIPTION
298
299 All basic math operations are overloaded if you declare your big
300 floats as
301
302     $float = new Math::BigFloat "2.123123123123123123123123123123123";
303
304 =over 2
305
306 =item number format
307
308 canonical strings have the form /[+-]\d+E[+-]\d+/ .  Input values can
309 have embedded whitespace.
310
311 =item Error returns 'NaN'
312
313 An input parameter was "Not a Number" or divide by zero or sqrt of
314 negative number.
315
316 =item Division is computed to 
317
318 C<max($Math::BigFloat::div_scale,length(dividend)+length(divisor))>
319 digits by default.
320 Also used for default sqrt scale.
321
322 =item Rounding is performed
323
324 according to the value of
325 C<$Math::BigFloat::rnd_mode>:
326
327   trunc     truncate the value
328   zero      round towards 0
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
333
334 The default is C<even> rounding.
335
336 =back
337
338 =head1 BUGS
339
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.
342
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,
348 as follows:
349
350   printf "%.3f\n", $bigfloat->ffround(-3);
351
352 =head1 AUTHOR
353
354 Mark Biggar
355
356 =cut