Define the U32_ALIGNMENT_REQUIRED only if it's not already defined.
[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);
3deb277d 7$VERSION = '0.01'; # never had version before
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},
16'/' => sub {new Math::BigFloat
a0d0e21e 17 $_[2]? scalar fdiv($_[1],${$_[0]}) :
18 scalar fdiv(${$_[0]},$_[1])},
a5f75d66 19'neg' => sub {new Math::BigFloat &fneg},
20'abs' => sub {new Math::BigFloat &fabs},
f216259d 21'int' => sub {new Math::BigInt &f2int},
a0d0e21e 22
23qw(
24"" stringify
250+ numify) # Order of arguments unsignificant
a5f75d66 26;
a0d0e21e 27
28sub new {
a5f75d66 29 my ($class) = shift;
30 my ($foo) = fnorm(shift);
a5f75d66 31 bless \$foo, $class;
a0d0e21e 32}
0e8b9368 33
a0d0e21e 34sub numify { 0 + "${$_[0]}" } # Not needed, additional overhead
35 # comparing to direct compilation based on
36 # stringify
37sub stringify {
38 my $n = ${$_[0]};
39
9b599b2a 40 my $minus = ($n =~ s/^([+-])// && $1 eq '-');
a0d0e21e 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 }
9b599b2a 55 $n = "-$n" if $minus;
a0d0e21e 56
57 # 1 while $n =~ s/(.*\d)(\d\d\d)/$1,$2/;
58
59 return $n;
60}
61
f216259d 62sub 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
a0d0e21e 69$div_scale = 40;
70
71# Rounding modes one of 'even', 'odd', '+inf', '-inf', 'zero' or 'trunc'.
72
73$rnd_mode = 'even';
74
75sub fadd; sub fsub; sub fmul; sub fdiv;
76sub fneg; sub fabs; sub fcmp;
77sub fround; sub ffround;
78sub fnorm; sub fsqrt;
79
a0d0e21e 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+$/.
83sub fnorm { #(string) return fnum_str
84 local($_) = @_;
85 s/\s+//g; # strip white space
db376a24 86 no warnings; # $4 and $5 below might legitimately be undefined
a0d0e21e 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
95sub norm { #(mantissa, exponent) return fnum_str
96 local($_, $exp) = @_;
3deb277d 97 $exp = 0 unless defined $exp;
a0d0e21e 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
112sub 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
120sub fabs { #(fnum_str) return fnum_str
121 local($_) = fnorm($_[$[]);
122 s/^-/+/; # mash sign
123 $_;
124}
125
126# multiplication
127sub 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}
a5f75d66 137
a0d0e21e 138# addition
139sub 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
152sub 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
159sub 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);
5d7098d5 171 &norm(&round(Math::BigInt::bdiv($xm.('0' x $scale),$ym),
172 Math::BigInt::babs($ym)),
a0d0e21e 173 $xe-$ye-$scale);
174 }
175}
a5f75d66 176
a0d0e21e 177# round int $q based on fraction $r/$base using $rnd_mode
178sub 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 ||
3deb277d 187 ($cmp == 0 && (
188 ($rnd_mode eq 'zero' ) ||
a0d0e21e 189 ($rnd_mode eq '-inf' && (substr($q,$[,1) eq '+')) ||
190 ($rnd_mode eq '+inf' && (substr($q,$[,1) eq '-')) ||
3deb277d 191 ($rnd_mode eq 'even' && $q =~ /[13579]$/ ) ||
192 ($rnd_mode eq 'odd' && $q =~ /[24680]$/ ) )
193 )
194 ) {
a0d0e21e 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
204sub 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}
a5f75d66 219
a0d0e21e 220# round $x at the 10 to the $scale digit place
221sub 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) {
5d7098d5 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);
a0d0e21e 239 } else {
240 &norm(&round(substr($xm,$[,$xe),
241 "+0".substr($xm,$[+$xe,1),"+10"), $scale);
242 }
243 }
244 }
245}
f216259d 246
247# Calculate the integer part of $x
248sub 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}
a0d0e21e 266
267# compare 2 values returns one of undef, <0, =0, >0
268# returns undef if either or both input value are not numbers
269sub 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 {
5dce09b1 275 local($xm,$xe,$ym,$ye) = split('E', $x."E$y");
276 if ($xm eq '+0' || $ym eq '+0') {
277 return $xm <=> $ym;
278 }
3deb277d 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);
a0d0e21e 290 }
291}
a5f75d66 292
a0d0e21e 293# square root by Newtons method.
294sub 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 }
a5f75d66 309 new Math::BigFloat &fround($guess, $scale);
a0d0e21e 310 }
311}
312
3131;
a5f75d66 314__END__
315
316=head1 NAME
317
318Math::BigFloat - Arbitrary length float math package
319
320=head1 SYNOPSIS
321
a2008d6d 322 use Math::BigFloat;
a5f75d66 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
339All basic math operations are overloaded if you declare your big
340floats as
341
342 $float = new Math::BigFloat "2.123123123123123123123123123123123";
343
344=over 2
345
346=item number format
347
348canonical strings have the form /[+-]\d+E[+-]\d+/ . Input values can
db696efe 349have embedded whitespace.
a5f75d66 350
351=item Error returns 'NaN'
352
353An input parameter was "Not a Number" or divide by zero or sqrt of
354negative number.
355
356=item Division is computed to
357
5d7098d5 358C<max($Math::BigFloat::div_scale,length(dividend)+length(divisor))>
359digits by default.
a5f75d66 360Also used for default sqrt scale.
361
5d7098d5 362=item Rounding is performed
363
364according to the value of
365C<$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
374The default is C<even> rounding.
375
a5f75d66 376=back
377
378=head1 BUGS
379
380The current version of this module is a preliminary version of the
381real thing that is currently (as of perl5.002) under development.
382
5d7098d5 383The printf subroutine does not use the value of
384C<$Math::BigFloat::rnd_mode> when rounding values for printing.
385Consequently, the way to print rounded values is
386to specify the number of digits both as an
387argument to C<ffround> and in the C<%f> printf string,
388as follows:
389
390 printf "%.3f\n", $bigfloat->ffround(-3);
391
a5f75d66 392=head1 AUTHOR
393
394Mark Biggar
395
396=cut