resync with mainline
[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
eaeb0b24 77 local $^W = 0; # $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 {
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}
a5f75d66 251
a0d0e21e 252# square root by Newtons method.
253sub 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 }
a5f75d66 268 new Math::BigFloat &fround($guess, $scale);
a0d0e21e 269 }
270}
271
2721;
a5f75d66 273__END__
274
275=head1 NAME
276
277Math::BigFloat - Arbitrary length float math package
278
279=head1 SYNOPSIS
280
a2008d6d 281 use Math::BigFloat;
a5f75d66 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
298All basic math operations are overloaded if you declare your big
299floats as
300
301 $float = new Math::BigFloat "2.123123123123123123123123123123123";
302
303=over 2
304
305=item number format
306
307canonical strings have the form /[+-]\d+E[+-]\d+/ . Input values can
db696efe 308have embedded whitespace.
a5f75d66 309
310=item Error returns 'NaN'
311
312An input parameter was "Not a Number" or divide by zero or sqrt of
313negative number.
314
315=item Division is computed to
316
5d7098d5 317C<max($Math::BigFloat::div_scale,length(dividend)+length(divisor))>
318digits by default.
a5f75d66 319Also used for default sqrt scale.
320
5d7098d5 321=item Rounding is performed
322
323according to the value of
324C<$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
333The default is C<even> rounding.
334
a5f75d66 335=back
336
337=head1 BUGS
338
339The current version of this module is a preliminary version of the
340real thing that is currently (as of perl5.002) under development.
341
5d7098d5 342The printf subroutine does not use the value of
343C<$Math::BigFloat::rnd_mode> when rounding values for printing.
344Consequently, the way to print rounded values is
345to specify the number of digits both as an
346argument to C<ffround> and in the C<%f> printf string,
347as follows:
348
349 printf "%.3f\n", $bigfloat->ffround(-3);
350
a5f75d66 351=head1 AUTHOR
352
353Mark Biggar
354
355=cut