avoid infinite recursion when Thread.pm croaks during
[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         ord($y) <=> ord($x)
244         ||
245         (  local($xm,$xe,$ym,$ye) = split('E', $x."E$y"),
246              (($xe <=> $ye) * (substr($x,$[,1).'1')
247              || Math::BigInt::cmp($xm,$ym))
248         );
249     }
250 }
251
252 # square root by Newtons method.
253 sub fsqrt { #(fnum_str[, scale]) return fnum_str
254     local($x, $scale) = (fnorm($_[$[]), $_[$[+1]);
255     if ($x eq 'NaN' || $x =~ /^-/) {
256         'NaN';
257     } elsif ($x eq '+0E+0') {
258         '+0E+0';
259     } else {
260         local($xm, $xe) = split('E',$x);
261         $scale = $div_scale if (!$scale);
262         $scale = length($xm)-1 if ($scale < length($xm)-1);
263         local($gs, $guess) = (1, sprintf("1E%+d", (length($xm)+$xe-1)/2));
264         while ($gs < 2*$scale) {
265             $guess = fmul(fadd($guess,fdiv($x,$guess,$gs*2)),".5");
266             $gs *= 2;
267         }
268         new Math::BigFloat &fround($guess, $scale);
269     }
270 }
271
272 1;
273 __END__
274
275 =head1 NAME
276
277 Math::BigFloat - Arbitrary length float math package
278
279 =head1 SYNOPSIS
280
281   use Math::BigFloat;
282   $f = Math::BigFloat->new($string);
283
284   $f->fadd(NSTR) return NSTR            addition
285   $f->fsub(NSTR) return NSTR            subtraction
286   $f->fmul(NSTR) return NSTR            multiplication
287   $f->fdiv(NSTR[,SCALE]) returns NSTR   division to SCALE places
288   $f->fneg() return NSTR                negation
289   $f->fabs() return NSTR                absolute value
290   $f->fcmp(NSTR) return CODE            compare undef,<0,=0,>0
291   $f->fround(SCALE) return NSTR         round to SCALE digits
292   $f->ffround(SCALE) return NSTR        round at SCALEth place
293   $f->fnorm() return (NSTR)             normalize
294   $f->fsqrt([SCALE]) return NSTR        sqrt to SCALE places
295
296 =head1 DESCRIPTION
297
298 All basic math operations are overloaded if you declare your big
299 floats as
300
301     $float = new Math::BigFloat "2.123123123123123123123123123123123";
302
303 =over 2
304
305 =item number format
306
307 canonical strings have the form /[+-]\d+E[+-]\d+/ .  Input values can
308 have embedded whitespace.
309
310 =item Error returns 'NaN'
311
312 An input parameter was "Not a Number" or divide by zero or sqrt of
313 negative number.
314
315 =item Division is computed to 
316
317 C<max($Math::BigFloat::div_scale,length(dividend)+length(divisor))>
318 digits by default.
319 Also used for default sqrt scale.
320
321 =item Rounding is performed
322
323 according to the value of
324 C<$Math::BigFloat::rnd_mode>:
325
326   trunc     truncate the value
327   zero      round towards 0
328   +inf      round towards +infinity (round up)
329   -inf      round towards -infinity (round down)
330   even      round to the nearest, .5 to the even digit
331   odd       round to the nearest, .5 to the odd digit
332
333 The default is C<even> rounding.
334
335 =back
336
337 =head1 BUGS
338
339 The current version of this module is a preliminary version of the
340 real thing that is currently (as of perl5.002) under development.
341
342 The printf subroutine does not use the value of
343 C<$Math::BigFloat::rnd_mode> when rounding values for printing.
344 Consequently, the way to print rounded values is
345 to specify the number of digits both as an
346 argument to C<ffround> and in the C<%f> printf string,
347 as follows:
348
349   printf "%.3f\n", $bigfloat->ffround(-3);
350
351 =head1 AUTHOR
352
353 Mark Biggar
354
355 =cut