Integrate with Sarathy.
[p5sagit/p5-mst-13.2.git] / lib / Math / BigFloat.pm
CommitLineData
a0d0e21e 1package Math::BigFloat;
2
3use Math::BigInt;
4
5use Exporter; # just for use to be happy
6@ISA = (Exporter);
7
a5f75d66 8use overload
9'+' => sub {new Math::BigFloat &fadd},
10'-' => sub {new Math::BigFloat
a0d0e21e 11 $_[2]? fsub($_[1],${$_[0]}) : fsub(${$_[0]},$_[1])},
5d7098d5 12'<=>' => sub {$_[2]? fcmp($_[1],${$_[0]}) : fcmp(${$_[0]},$_[1])},
13'cmp' => sub {$_[2]? ($_[1] cmp ${$_[0]}) : (${$_[0]} cmp $_[1])},
a5f75d66 14'*' => sub {new Math::BigFloat &fmul},
15'/' => sub {new Math::BigFloat
a0d0e21e 16 $_[2]? scalar fdiv($_[1],${$_[0]}) :
17 scalar fdiv(${$_[0]},$_[1])},
a5f75d66 18'neg' => sub {new Math::BigFloat &fneg},
19'abs' => sub {new Math::BigFloat &fabs},
a0d0e21e 20
21qw(
22"" stringify
230+ numify) # Order of arguments unsignificant
a5f75d66 24;
a0d0e21e 25
26sub new {
a5f75d66 27 my ($class) = shift;
28 my ($foo) = fnorm(shift);
a5f75d66 29 bless \$foo, $class;
a0d0e21e 30}
0e8b9368 31
a0d0e21e 32sub numify { 0 + "${$_[0]}" } # Not needed, additional overhead
33 # comparing to direct compilation based on
34 # stringify
35sub stringify {
36 my $n = ${$_[0]};
37
9b599b2a 38 my $minus = ($n =~ s/^([+-])// && $1 eq '-');
a0d0e21e 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 }
9b599b2a 53 $n = "-$n" if $minus;
a0d0e21e 54
55 # 1 while $n =~ s/(.*\d)(\d\d\d)/$1,$2/;
56
57 return $n;
58}
59
a0d0e21e 60$div_scale = 40;
61
62# Rounding modes one of 'even', 'odd', '+inf', '-inf', 'zero' or 'trunc'.
63
64$rnd_mode = 'even';
65
66sub fadd; sub fsub; sub fmul; sub fdiv;
67sub fneg; sub fabs; sub fcmp;
68sub fround; sub ffround;
69sub fnorm; sub fsqrt;
70
a0d0e21e 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+$/.
74sub fnorm { #(string) return fnum_str
75 local($_) = @_;
76 s/\s+//g; # strip white space
db376a24 77 no warnings; # $4 and $5 below might legitimately be undefined
a0d0e21e 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
86sub 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
102sub 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
110sub fabs { #(fnum_str) return fnum_str
111 local($_) = fnorm($_[$[]);
112 s/^-/+/; # mash sign
113 $_;
114}
115
116# multiplication
117sub 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}
a5f75d66 127
a0d0e21e 128# addition
129sub 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
142sub 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
149sub 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);
5d7098d5 161 &norm(&round(Math::BigInt::bdiv($xm.('0' x $scale),$ym),
162 Math::BigInt::babs($ym)),
a0d0e21e 163 $xe-$ye-$scale);
164 }
165}
a5f75d66 166
a0d0e21e 167# round int $q based on fraction $r/$base using $rnd_mode
168sub 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
192sub 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}
a5f75d66 207
a0d0e21e 208# round $x at the 10 to the $scale digit place
209sub 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) {
5d7098d5 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);
a0d0e21e 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
237sub 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 {
5dce09b1 243 local($xm,$xe,$ym,$ye) = split('E', $x."E$y");
244 if ($xm eq '+0' || $ym eq '+0') {
245 return $xm <=> $ym;
246 }
a0d0e21e 247 ord($y) <=> ord($x)
5dce09b1 248 || ($xe <=> $ye) * (substr($x,$[,1).'1')
249 || Math::BigInt::cmp($xm,$ym);
a0d0e21e 250 }
251}
a5f75d66 252
a0d0e21e 253# square root by Newtons method.
254sub 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 }
a5f75d66 269 new Math::BigFloat &fround($guess, $scale);
a0d0e21e 270 }
271}
272
2731;
a5f75d66 274__END__
275
276=head1 NAME
277
278Math::BigFloat - Arbitrary length float math package
279
280=head1 SYNOPSIS
281
a2008d6d 282 use Math::BigFloat;
a5f75d66 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
299All basic math operations are overloaded if you declare your big
300floats as
301
302 $float = new Math::BigFloat "2.123123123123123123123123123123123";
303
304=over 2
305
306=item number format
307
308canonical strings have the form /[+-]\d+E[+-]\d+/ . Input values can
db696efe 309have embedded whitespace.
a5f75d66 310
311=item Error returns 'NaN'
312
313An input parameter was "Not a Number" or divide by zero or sqrt of
314negative number.
315
316=item Division is computed to
317
5d7098d5 318C<max($Math::BigFloat::div_scale,length(dividend)+length(divisor))>
319digits by default.
a5f75d66 320Also used for default sqrt scale.
321
5d7098d5 322=item Rounding is performed
323
324according to the value of
325C<$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
334The default is C<even> rounding.
335
a5f75d66 336=back
337
338=head1 BUGS
339
340The current version of this module is a preliminary version of the
341real thing that is currently (as of perl5.002) under development.
342
5d7098d5 343The printf subroutine does not use the value of
344C<$Math::BigFloat::rnd_mode> when rounding values for printing.
345Consequently, the way to print rounded values is
346to specify the number of digits both as an
347argument to C<ffround> and in the C<%f> printf string,
348as follows:
349
350 printf "%.3f\n", $bigfloat->ffround(-3);
351
a5f75d66 352=head1 AUTHOR
353
354Mark Biggar
355
356=cut