Additional dependencies; should help for parallel makes
[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);
288d023a 7$VERSION = '0.03';
a0d0e21e 8
a5f75d66 9use overload
10'+' => sub {new Math::BigFloat &fadd},
11'-' => sub {new Math::BigFloat
a0d0e21e 12 $_[2]? fsub($_[1],${$_[0]}) : fsub(${$_[0]},$_[1])},
5d7098d5 13'<=>' => sub {$_[2]? fcmp($_[1],${$_[0]}) : fcmp(${$_[0]},$_[1])},
14'cmp' => sub {$_[2]? ($_[1] cmp ${$_[0]}) : (${$_[0]} cmp $_[1])},
a5f75d66 15'*' => sub {new Math::BigFloat &fmul},
288d023a 16'/' => sub {new Math::BigFloat
a0d0e21e 17 $_[2]? scalar fdiv($_[1],${$_[0]}) :
18 scalar fdiv(${$_[0]},$_[1])},
288d023a 19'%' => sub {new Math::BigFloat
20 $_[2]? scalar fmod($_[1],${$_[0]}) :
21 scalar fmod(${$_[0]},$_[1])},
a5f75d66 22'neg' => sub {new Math::BigFloat &fneg},
23'abs' => sub {new Math::BigFloat &fabs},
f216259d 24'int' => sub {new Math::BigInt &f2int},
a0d0e21e 25
26qw(
27"" stringify
280+ numify) # Order of arguments unsignificant
a5f75d66 29;
a0d0e21e 30
31sub new {
a5f75d66 32 my ($class) = shift;
33 my ($foo) = fnorm(shift);
a5f75d66 34 bless \$foo, $class;
a0d0e21e 35}
0e8b9368 36
a0d0e21e 37sub numify { 0 + "${$_[0]}" } # Not needed, additional overhead
38 # comparing to direct compilation based on
39 # stringify
40sub stringify {
41 my $n = ${$_[0]};
42
9b599b2a 43 my $minus = ($n =~ s/^([+-])// && $1 eq '-');
a0d0e21e 44 $n =~ s/E//;
45
46 $n =~ s/([-+]\d+)$//;
47
48 my $e = $1;
49 my $ln = length($n);
50
288d023a 51 if ( defined $e )
52 {
53 if ($e > 0) {
54 $n .= "0" x $e . '.';
55 } elsif (abs($e) < $ln) {
56 substr($n, $ln + $e, 0) = '.';
57 } else {
58 $n = '.' . ("0" x (abs($e) - $ln)) . $n;
59 }
a0d0e21e 60 }
9b599b2a 61 $n = "-$n" if $minus;
a0d0e21e 62
63 # 1 while $n =~ s/(.*\d)(\d\d\d)/$1,$2/;
64
65 return $n;
66}
67
f216259d 68sub import {
69 shift;
70 return unless @_;
71 die "unknown import: @_" unless @_ == 1 and $_[0] eq ':constant';
72 overload::constant float => sub {Math::BigFloat->new(shift)};
73}
74
a0d0e21e 75$div_scale = 40;
76
77# Rounding modes one of 'even', 'odd', '+inf', '-inf', 'zero' or 'trunc'.
78
79$rnd_mode = 'even';
80
81sub fadd; sub fsub; sub fmul; sub fdiv;
82sub fneg; sub fabs; sub fcmp;
83sub fround; sub ffround;
84sub fnorm; sub fsqrt;
85
a0d0e21e 86# Convert a number to canonical string form.
87# Takes something that looks like a number and converts it to
88# the form /^[+-]\d+E[+-]\d+$/.
89sub fnorm { #(string) return fnum_str
90 local($_) = @_;
91 s/\s+//g; # strip white space
db376a24 92 no warnings; # $4 and $5 below might legitimately be undefined
a0d0e21e 93 if (/^([+-]?)(\d*)(\.(\d*))?([Ee]([+-]?\d+))?$/ && "$2$4" ne '') {
94 &norm(($1 ? "$1$2$4" : "+$2$4"),(($4 ne '') ? $6-length($4) : $6));
95 } else {
96 'NaN';
97 }
98}
99
100# normalize number -- for internal use
101sub norm { #(mantissa, exponent) return fnum_str
102 local($_, $exp) = @_;
3deb277d 103 $exp = 0 unless defined $exp;
a0d0e21e 104 if ($_ eq 'NaN') {
105 'NaN';
106 } else {
107 s/^([+-])0+/$1/; # strip leading zeros
108 if (length($_) == 1) {
109 '+0E+0';
110 } else {
111 $exp += length($1) if (s/(0+)$//); # strip trailing zeros
112 sprintf("%sE%+ld", $_, $exp);
113 }
114 }
115}
116
117# negation
118sub fneg { #(fnum_str) return fnum_str
119 local($_) = fnorm($_[$[]);
120 vec($_,0,8) ^= ord('+') ^ ord('-') unless $_ eq '+0E+0'; # flip sign
121 s/^H/N/;
122 $_;
123}
124
125# absolute value
126sub fabs { #(fnum_str) return fnum_str
127 local($_) = fnorm($_[$[]);
128 s/^-/+/; # mash sign
129 $_;
130}
131
132# multiplication
133sub fmul { #(fnum_str, fnum_str) return fnum_str
134 local($x,$y) = (fnorm($_[$[]),fnorm($_[$[+1]));
135 if ($x eq 'NaN' || $y eq 'NaN') {
136 'NaN';
137 } else {
138 local($xm,$xe) = split('E',$x);
139 local($ym,$ye) = split('E',$y);
140 &norm(Math::BigInt::bmul($xm,$ym),$xe+$ye);
141 }
142}
a5f75d66 143
a0d0e21e 144# addition
145sub fadd { #(fnum_str, fnum_str) return fnum_str
146 local($x,$y) = (fnorm($_[$[]),fnorm($_[$[+1]));
147 if ($x eq 'NaN' || $y eq 'NaN') {
148 'NaN';
149 } else {
150 local($xm,$xe) = split('E',$x);
151 local($ym,$ye) = split('E',$y);
152 ($xm,$xe,$ym,$ye) = ($ym,$ye,$xm,$xe) if ($xe < $ye);
153 &norm(Math::BigInt::badd($ym,$xm.('0' x ($xe-$ye))),$ye);
154 }
155}
156
157# subtraction
158sub fsub { #(fnum_str, fnum_str) return fnum_str
288d023a 159 fadd($_[$[],fneg($_[$[+1]));
a0d0e21e 160}
161
162# division
163# args are dividend, divisor, scale (optional)
164# result has at most max(scale, length(dividend), length(divisor)) digits
165sub fdiv #(fnum_str, fnum_str[,scale]) return fnum_str
166{
167 local($x,$y,$scale) = (fnorm($_[$[]),fnorm($_[$[+1]),$_[$[+2]);
168 if ($x eq 'NaN' || $y eq 'NaN' || $y eq '+0E+0') {
169 'NaN';
170 } else {
171 local($xm,$xe) = split('E',$x);
172 local($ym,$ye) = split('E',$y);
173 $scale = $div_scale if (!$scale);
174 $scale = length($xm)-1 if (length($xm)-1 > $scale);
175 $scale = length($ym)-1 if (length($ym)-1 > $scale);
176 $scale = $scale + length($ym) - length($xm);
5d7098d5 177 &norm(&round(Math::BigInt::bdiv($xm.('0' x $scale),$ym),
178 Math::BigInt::babs($ym)),
a0d0e21e 179 $xe-$ye-$scale);
180 }
181}
a5f75d66 182
288d023a 183# modular division
184# args are dividend, divisor
185sub fmod #(fnum_str, fnum_str) return fnum_str
186{
187 local($x,$y) = (fnorm($_[$[]),fnorm($_[$[+1]));
188 if ($x eq 'NaN' || $y eq 'NaN' || $y eq '+0E+0') {
189 'NaN';
190 } else {
191 local($xm,$xe) = split('E',$x);
192 local($ym,$ye) = split('E',$y);
193 if ( $xe < $ye )
194 {
195 $ym .= ('0' x ($ye-$xe));
196 }
197 else
198 {
199 $xm .= ('0' x ($xe-$ye));
200 }
201 &norm(Math::BigInt::bmod($xm,$ym));
202 }
203}
a0d0e21e 204# round int $q based on fraction $r/$base using $rnd_mode
205sub round { #(int_str, int_str, int_str) return int_str
206 local($q,$r,$base) = @_;
207 if ($q eq 'NaN' || $r eq 'NaN') {
208 'NaN';
209 } elsif ($rnd_mode eq 'trunc') {
210 $q; # just truncate
211 } else {
212 local($cmp) = Math::BigInt::bcmp(Math::BigInt::bmul($r,'+2'),$base);
213 if ( $cmp < 0 ||
3deb277d 214 ($cmp == 0 && (
215 ($rnd_mode eq 'zero' ) ||
a0d0e21e 216 ($rnd_mode eq '-inf' && (substr($q,$[,1) eq '+')) ||
217 ($rnd_mode eq '+inf' && (substr($q,$[,1) eq '-')) ||
288d023a 218 ($rnd_mode eq 'even' && $q =~ /[24680]$/ ) ||
219 ($rnd_mode eq 'odd' && $q =~ /[13579]$/ ) )
220 )
3deb277d 221 ) {
a0d0e21e 222 $q; # round down
223 } else {
224 Math::BigInt::badd($q, ((substr($q,$[,1) eq '-') ? '-1' : '+1'));
225 # round up
226 }
227 }
228}
229
230# round the mantissa of $x to $scale digits
231sub fround { #(fnum_str, scale) return fnum_str
232 local($x,$scale) = (fnorm($_[$[]),$_[$[+1]);
233 if ($x eq 'NaN' || $scale <= 0) {
234 $x;
235 } else {
236 local($xm,$xe) = split('E',$x);
237 if (length($xm)-1 <= $scale) {
238 $x;
239 } else {
288d023a 240 &norm(&round(substr($xm,$[,$scale+1),
241 "+0".substr($xm,$[+$scale+1),"+1"."0" x length(substr($xm,$[+$scale+1))),
a0d0e21e 242 $xe+length($xm)-$scale-1);
243 }
244 }
245}
a5f75d66 246
a0d0e21e 247# round $x at the 10 to the $scale digit place
248sub ffround { #(fnum_str, scale) return fnum_str
249 local($x,$scale) = (fnorm($_[$[]),$_[$[+1]);
250 if ($x eq 'NaN') {
251 'NaN';
252 } else {
253 local($xm,$xe) = split('E',$x);
254 if ($xe >= $scale) {
255 $x;
256 } else {
257 $xe = length($xm)+$xe-$scale;
258 if ($xe < 1) {
259 '+0E+0';
260 } elsif ($xe == 1) {
5d7098d5 261 # The first substr preserves the sign, passing a non-
262 # normalized "-0" to &round when rounding -0.006 (for
263 # example), purely so &round won't lose the sign.
264 &norm(&round(substr($xm,$[,1).'0',
288d023a 265 "+0".substr($xm,$[+1),
266 "+1"."0" x length(substr($xm,$[+1))), $scale);
a0d0e21e 267 } else {
268 &norm(&round(substr($xm,$[,$xe),
288d023a 269 "+0".substr($xm,$[+$xe),
270 "+1"."0" x length(substr($xm,$[+$xe))), $scale);
a0d0e21e 271 }
272 }
273 }
274}
f216259d 275
276# Calculate the integer part of $x
277sub f2int { #(fnum_str) return inum_str
278 local($x) = ${$_[$[]};
279 if ($x eq 'NaN') {
280 die "Attempt to take int(NaN)";
281 } else {
282 local($xm,$xe) = split('E',$x);
283 if ($xe >= 0) {
284 $xm . '0' x $xe;
285 } else {
286 $xe = length($xm)+$xe;
287 if ($xe <= 1) {
288 '+0';
289 } else {
290 substr($xm,$[,$xe);
291 }
292 }
293 }
294}
288d023a 295
a0d0e21e 296# compare 2 values returns one of undef, <0, =0, >0
297# returns undef if either or both input value are not numbers
298sub fcmp #(fnum_str, fnum_str) return cond_code
299{
300 local($x, $y) = (fnorm($_[$[]),fnorm($_[$[+1]));
301 if ($x eq "NaN" || $y eq "NaN") {
302 undef;
303 } else {
5dce09b1 304 local($xm,$xe,$ym,$ye) = split('E', $x."E$y");
305 if ($xm eq '+0' || $ym eq '+0') {
306 return $xm <=> $ym;
307 }
3deb277d 308 if ( $xe < $ye ) # adjust the exponents to be equal
309 {
310 $ym .= '0' x ($ye - $xe);
311 $ye = $xe;
312 }
313 elsif ( $ye < $xe ) # same here
314 {
315 $xm .= '0' x ($xe - $ye);
316 $xe = $ye;
317 }
318 return Math::BigInt::cmp($xm,$ym);
a0d0e21e 319 }
320}
a5f75d66 321
a0d0e21e 322# square root by Newtons method.
323sub fsqrt { #(fnum_str[, scale]) return fnum_str
324 local($x, $scale) = (fnorm($_[$[]), $_[$[+1]);
325 if ($x eq 'NaN' || $x =~ /^-/) {
326 'NaN';
327 } elsif ($x eq '+0E+0') {
328 '+0E+0';
329 } else {
330 local($xm, $xe) = split('E',$x);
331 $scale = $div_scale if (!$scale);
332 $scale = length($xm)-1 if ($scale < length($xm)-1);
333 local($gs, $guess) = (1, sprintf("1E%+d", (length($xm)+$xe-1)/2));
334 while ($gs < 2*$scale) {
335 $guess = fmul(fadd($guess,fdiv($x,$guess,$gs*2)),".5");
336 $gs *= 2;
337 }
a5f75d66 338 new Math::BigFloat &fround($guess, $scale);
a0d0e21e 339 }
340}
341
3421;
a5f75d66 343__END__
344
345=head1 NAME
346
347Math::BigFloat - Arbitrary length float math package
348
349=head1 SYNOPSIS
350
a2008d6d 351 use Math::BigFloat;
a5f75d66 352 $f = Math::BigFloat->new($string);
353
354 $f->fadd(NSTR) return NSTR addition
355 $f->fsub(NSTR) return NSTR subtraction
356 $f->fmul(NSTR) return NSTR multiplication
357 $f->fdiv(NSTR[,SCALE]) returns NSTR division to SCALE places
288d023a 358 $f->fmod(NSTR) returns NSTR modular remainder
a5f75d66 359 $f->fneg() return NSTR negation
360 $f->fabs() return NSTR absolute value
361 $f->fcmp(NSTR) return CODE compare undef,<0,=0,>0
362 $f->fround(SCALE) return NSTR round to SCALE digits
363 $f->ffround(SCALE) return NSTR round at SCALEth place
364 $f->fnorm() return (NSTR) normalize
365 $f->fsqrt([SCALE]) return NSTR sqrt to SCALE places
366
367=head1 DESCRIPTION
368
369All basic math operations are overloaded if you declare your big
370floats as
371
372 $float = new Math::BigFloat "2.123123123123123123123123123123123";
373
374=over 2
375
376=item number format
377
378canonical strings have the form /[+-]\d+E[+-]\d+/ . Input values can
db696efe 379have embedded whitespace.
a5f75d66 380
381=item Error returns 'NaN'
382
383An input parameter was "Not a Number" or divide by zero or sqrt of
384negative number.
385
288d023a 386=item Division is computed to
a5f75d66 387
5d7098d5 388C<max($Math::BigFloat::div_scale,length(dividend)+length(divisor))>
389digits by default.
a5f75d66 390Also used for default sqrt scale.
391
5d7098d5 392=item Rounding is performed
393
394according to the value of
395C<$Math::BigFloat::rnd_mode>:
396
397 trunc truncate the value
398 zero round towards 0
399 +inf round towards +infinity (round up)
400 -inf round towards -infinity (round down)
401 even round to the nearest, .5 to the even digit
402 odd round to the nearest, .5 to the odd digit
403
404The default is C<even> rounding.
405
a5f75d66 406=back
407
408=head1 BUGS
409
410The current version of this module is a preliminary version of the
411real thing that is currently (as of perl5.002) under development.
412
5d7098d5 413The printf subroutine does not use the value of
414C<$Math::BigFloat::rnd_mode> when rounding values for printing.
415Consequently, the way to print rounded values is
416to specify the number of digits both as an
417argument to C<ffround> and in the C<%f> printf string,
418as follows:
419
420 printf "%.3f\n", $bigfloat->ffround(-3);
421
a5f75d66 422=head1 AUTHOR
423
424Mark Biggar
288d023a 425Patches by John Peacock Apr 2001
a5f75d66 426=cut