overload int()
[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 $VERSION = '0.01';      # never had version before
8
9 use overload
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},
22
23 qw(
24 ""      stringify
25 0+      numify)                 # Order of arguments unsignificant
26 ;
27
28 sub new {
29   my ($class) = shift;
30   my ($foo) = fnorm(shift);
31   bless \$foo, $class;
32 }
33
34 sub numify { 0 + "${$_[0]}" }   # Not needed, additional overhead
35                                 # comparing to direct compilation based on
36                                 # stringify
37 sub stringify {
38     my $n = ${$_[0]};
39
40     my $minus = ($n =~ s/^([+-])// && $1 eq '-');
41     $n =~ s/E//;
42
43     $n =~ s/([-+]\d+)$//;
44
45     my $e = $1;
46     my $ln = length($n);
47
48     if ($e > 0) {
49         $n .= "0" x $e . '.';
50     } elsif (abs($e) < $ln) {
51         substr($n, $ln + $e, 0) = '.';
52     } else {
53         $n = '.' . ("0" x (abs($e) - $ln)) . $n;
54     }
55     $n = "-$n" if $minus;
56
57     # 1 while $n =~ s/(.*\d)(\d\d\d)/$1,$2/;
58
59     return $n;
60 }
61
62 sub import {
63   shift;
64   return unless @_;
65   die "unknown import: @_" unless @_ == 1 and $_[0] eq ':constant';
66   overload::constant float => sub {Math::BigFloat->new(shift)};
67 }
68
69 $div_scale = 40;
70
71 # Rounding modes one of 'even', 'odd', '+inf', '-inf', 'zero' or 'trunc'.
72
73 $rnd_mode = 'even';
74
75 sub fadd; sub fsub; sub fmul; sub fdiv;
76 sub fneg; sub fabs; sub fcmp;
77 sub fround; sub ffround;
78 sub fnorm; sub fsqrt;
79
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
84     local($_) = @_;
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));
89     } else {
90         'NaN';
91     }
92 }
93
94 # normalize number -- for internal use
95 sub norm { #(mantissa, exponent) return fnum_str
96     local($_, $exp) = @_;
97         $exp = 0 unless defined $exp;
98     if ($_ eq 'NaN') {
99         'NaN';
100     } else {
101         s/^([+-])0+/$1/;                        # strip leading zeros
102         if (length($_) == 1) {
103             '+0E+0';
104         } else {
105             $exp += length($1) if (s/(0+)$//);  # strip trailing zeros
106             sprintf("%sE%+ld", $_, $exp);
107         }
108     }
109 }
110
111 # negation
112 sub fneg { #(fnum_str) return fnum_str
113     local($_) = fnorm($_[$[]);
114     vec($_,0,8) ^= ord('+') ^ ord('-') unless $_ eq '+0E+0'; # flip sign
115     s/^H/N/;
116     $_;
117 }
118
119 # absolute value
120 sub fabs { #(fnum_str) return fnum_str
121     local($_) = fnorm($_[$[]);
122     s/^-/+/;                                   # mash sign
123     $_;
124 }
125
126 # multiplication
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') {
130         'NaN';
131     } else {
132         local($xm,$xe) = split('E',$x);
133         local($ym,$ye) = split('E',$y);
134         &norm(Math::BigInt::bmul($xm,$ym),$xe+$ye);
135     }
136 }
137
138 # addition
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') {
142         'NaN';
143     } else {
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);
148     }
149 }
150
151 # subtraction
152 sub fsub { #(fnum_str, fnum_str) return fnum_str
153     fadd($_[$[],fneg($_[$[+1]));    
154 }
155
156 # division
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
160 {
161     local($x,$y,$scale) = (fnorm($_[$[]),fnorm($_[$[+1]),$_[$[+2]);
162     if ($x eq 'NaN' || $y eq 'NaN' || $y eq '+0E+0') {
163         'NaN';
164     } else {
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)),
173             $xe-$ye-$scale);
174     }
175 }
176
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') {
181         'NaN';
182     } elsif ($rnd_mode eq 'trunc') {
183         $q;                         # just truncate
184     } else {
185         local($cmp) = Math::BigInt::bcmp(Math::BigInt::bmul($r,'+2'),$base);
186         if ( $cmp < 0 ||
187                  ($cmp == 0 &&                                          (
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]$/        )    )
193                   ) 
194                 ) {
195             $q;                     # round down
196         } else {
197             Math::BigInt::badd($q, ((substr($q,$[,1) eq '-') ? '-1' : '+1'));
198                                     # round up
199         }
200     }
201 }
202
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) {
207         $x;
208     } else {
209         local($xm,$xe) = split('E',$x);
210         if (length($xm)-1 <= $scale) {
211             $x;
212         } else {
213             &norm(&round(substr($xm,$[,$scale+1),
214                          "+0".substr($xm,$[+$scale+1,1),"+10"),
215                   $xe+length($xm)-$scale-1);
216         }
217     }
218 }
219
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]);
223     if ($x eq 'NaN') {
224         'NaN';
225     } else {
226         local($xm,$xe) = split('E',$x);
227         if ($xe >= $scale) {
228             $x;
229         } else {
230             $xe = length($xm)+$xe-$scale;
231             if ($xe < 1) {
232                 '+0E+0';
233             } elsif ($xe == 1) {
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);
239             } else {
240                 &norm(&round(substr($xm,$[,$xe),
241                       "+0".substr($xm,$[+$xe,1),"+10"), $scale);
242             }
243         }
244     }
245 }
246
247 # Calculate the integer part of $x
248 sub f2int { #(fnum_str) return inum_str
249     local($x) = ${$_[$[]};
250     if ($x eq 'NaN') {
251         die "Attempt to take int(NaN)";
252     } else {
253         local($xm,$xe) = split('E',$x);
254         if ($xe >= 0) {
255             $xm . '0' x $xe;
256         } else {
257             $xe = length($xm)+$xe;
258             if ($xe <= 1) {
259                 '+0';
260             } else {
261                 substr($xm,$[,$xe);
262             }
263         }
264     }
265 }
266     
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
270 {
271     local($x, $y) = (fnorm($_[$[]),fnorm($_[$[+1]));
272     if ($x eq "NaN" || $y eq "NaN") {
273         undef;
274     } else {
275         local($xm,$xe,$ym,$ye) = split('E', $x."E$y");
276         if ($xm eq '+0' || $ym eq '+0') {
277             return $xm <=> $ym;
278         }
279         if ( $xe < $ye )        # adjust the exponents to be equal
280         {
281                 $ym .= '0' x ($ye - $xe);
282                 $ye = $xe;
283         }
284         elsif ( $ye < $xe )     # same here
285         {
286                 $xm .= '0' x ($xe - $ye);
287                 $xe = $ye;
288         }
289         return Math::BigInt::cmp($xm,$ym);
290     }
291 }
292
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 =~ /^-/) {
297         'NaN';
298     } elsif ($x eq '+0E+0') {
299         '+0E+0';
300     } else {
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");
307             $gs *= 2;
308         }
309         new Math::BigFloat &fround($guess, $scale);
310     }
311 }
312
313 1;
314 __END__
315
316 =head1 NAME
317
318 Math::BigFloat - Arbitrary length float math package
319
320 =head1 SYNOPSIS
321
322   use Math::BigFloat;
323   $f = Math::BigFloat->new($string);
324
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
336
337 =head1 DESCRIPTION
338
339 All basic math operations are overloaded if you declare your big
340 floats as
341
342     $float = new Math::BigFloat "2.123123123123123123123123123123123";
343
344 =over 2
345
346 =item number format
347
348 canonical strings have the form /[+-]\d+E[+-]\d+/ .  Input values can
349 have embedded whitespace.
350
351 =item Error returns 'NaN'
352
353 An input parameter was "Not a Number" or divide by zero or sqrt of
354 negative number.
355
356 =item Division is computed to 
357
358 C<max($Math::BigFloat::div_scale,length(dividend)+length(divisor))>
359 digits by default.
360 Also used for default sqrt scale.
361
362 =item Rounding is performed
363
364 according to the value of
365 C<$Math::BigFloat::rnd_mode>:
366
367   trunc     truncate the value
368   zero      round towards 0
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
373
374 The default is C<even> rounding.
375
376 =back
377
378 =head1 BUGS
379
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.
382
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,
388 as follows:
389
390   printf "%.3f\n", $bigfloat->ffround(-3);
391
392 =head1 AUTHOR
393
394 Mark Biggar
395
396 =cut