undo change#2571; C<use File::Spec> instead
[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])},
a5f75d66 12'<=>' => sub {new Math::BigFloat
a0d0e21e 13 $_[2]? fcmp($_[1],${$_[0]}) : fcmp(${$_[0]},$_[1])},
a5f75d66 14'cmp' => sub {new Math::BigFloat
a0d0e21e 15 $_[2]? ($_[1] cmp ${$_[0]}) : (${$_[0]} cmp $_[1])},
a5f75d66 16'*' => sub {new Math::BigFloat &fmul},
17'/' => sub {new Math::BigFloat
a0d0e21e 18 $_[2]? scalar fdiv($_[1],${$_[0]}) :
19 scalar fdiv(${$_[0]},$_[1])},
a5f75d66 20'neg' => sub {new Math::BigFloat &fneg},
21'abs' => sub {new Math::BigFloat &fabs},
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);
31 panic("Not a number initialized to Math::BigFloat") if $foo eq "NaN";
32 bless \$foo, $class;
a0d0e21e 33}
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
a0d0e21e 62$div_scale = 40;
63
64# Rounding modes one of 'even', 'odd', '+inf', '-inf', 'zero' or 'trunc'.
65
66$rnd_mode = 'even';
67
68sub fadd; sub fsub; sub fmul; sub fdiv;
69sub fneg; sub fabs; sub fcmp;
70sub fround; sub ffround;
71sub fnorm; sub fsqrt;
72
a0d0e21e 73# Convert a number to canonical string form.
74# Takes something that looks like a number and converts it to
75# the form /^[+-]\d+E[+-]\d+$/.
76sub fnorm { #(string) return fnum_str
77 local($_) = @_;
78 s/\s+//g; # strip white space
79 if (/^([+-]?)(\d*)(\.(\d*))?([Ee]([+-]?\d+))?$/ && "$2$4" ne '') {
80 &norm(($1 ? "$1$2$4" : "+$2$4"),(($4 ne '') ? $6-length($4) : $6));
81 } else {
82 'NaN';
83 }
84}
85
86# normalize number -- for internal use
87sub norm { #(mantissa, exponent) return fnum_str
88 local($_, $exp) = @_;
89 if ($_ eq 'NaN') {
90 'NaN';
91 } else {
92 s/^([+-])0+/$1/; # strip leading zeros
93 if (length($_) == 1) {
94 '+0E+0';
95 } else {
96 $exp += length($1) if (s/(0+)$//); # strip trailing zeros
97 sprintf("%sE%+ld", $_, $exp);
98 }
99 }
100}
101
102# negation
103sub fneg { #(fnum_str) return fnum_str
104 local($_) = fnorm($_[$[]);
105 vec($_,0,8) ^= ord('+') ^ ord('-') unless $_ eq '+0E+0'; # flip sign
106 s/^H/N/;
107 $_;
108}
109
110# absolute value
111sub fabs { #(fnum_str) return fnum_str
112 local($_) = fnorm($_[$[]);
113 s/^-/+/; # mash sign
114 $_;
115}
116
117# multiplication
118sub fmul { #(fnum_str, fnum_str) return fnum_str
119 local($x,$y) = (fnorm($_[$[]),fnorm($_[$[+1]));
120 if ($x eq 'NaN' || $y eq 'NaN') {
121 'NaN';
122 } else {
123 local($xm,$xe) = split('E',$x);
124 local($ym,$ye) = split('E',$y);
125 &norm(Math::BigInt::bmul($xm,$ym),$xe+$ye);
126 }
127}
a5f75d66 128
a0d0e21e 129# addition
130sub fadd { #(fnum_str, fnum_str) return fnum_str
131 local($x,$y) = (fnorm($_[$[]),fnorm($_[$[+1]));
132 if ($x eq 'NaN' || $y eq 'NaN') {
133 'NaN';
134 } else {
135 local($xm,$xe) = split('E',$x);
136 local($ym,$ye) = split('E',$y);
137 ($xm,$xe,$ym,$ye) = ($ym,$ye,$xm,$xe) if ($xe < $ye);
138 &norm(Math::BigInt::badd($ym,$xm.('0' x ($xe-$ye))),$ye);
139 }
140}
141
142# subtraction
143sub fsub { #(fnum_str, fnum_str) return fnum_str
144 fadd($_[$[],fneg($_[$[+1]));
145}
146
147# division
148# args are dividend, divisor, scale (optional)
149# result has at most max(scale, length(dividend), length(divisor)) digits
150sub fdiv #(fnum_str, fnum_str[,scale]) return fnum_str
151{
152 local($x,$y,$scale) = (fnorm($_[$[]),fnorm($_[$[+1]),$_[$[+2]);
153 if ($x eq 'NaN' || $y eq 'NaN' || $y eq '+0E+0') {
154 'NaN';
155 } else {
156 local($xm,$xe) = split('E',$x);
157 local($ym,$ye) = split('E',$y);
158 $scale = $div_scale if (!$scale);
159 $scale = length($xm)-1 if (length($xm)-1 > $scale);
160 $scale = length($ym)-1 if (length($ym)-1 > $scale);
161 $scale = $scale + length($ym) - length($xm);
162 &norm(&round(Math::BigInt::bdiv($xm.('0' x $scale),$ym),$ym),
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) {
222 &norm(&round('+0',"+0".substr($xm,$[+1,1),"+10"), $scale);
223 } else {
224 &norm(&round(substr($xm,$[,$xe),
225 "+0".substr($xm,$[+$xe,1),"+10"), $scale);
226 }
227 }
228 }
229}
230
231# compare 2 values returns one of undef, <0, =0, >0
232# returns undef if either or both input value are not numbers
233sub fcmp #(fnum_str, fnum_str) return cond_code
234{
235 local($x, $y) = (fnorm($_[$[]),fnorm($_[$[+1]));
236 if ($x eq "NaN" || $y eq "NaN") {
237 undef;
238 } else {
239 ord($y) <=> ord($x)
240 ||
241 ( local($xm,$xe,$ym,$ye) = split('E', $x."E$y"),
242 (($xe <=> $ye) * (substr($x,$[,1).'1')
243 || Math::BigInt::cmp($xm,$ym))
244 );
245 }
246}
a5f75d66 247
a0d0e21e 248# square root by Newtons method.
249sub fsqrt { #(fnum_str[, scale]) return fnum_str
250 local($x, $scale) = (fnorm($_[$[]), $_[$[+1]);
251 if ($x eq 'NaN' || $x =~ /^-/) {
252 'NaN';
253 } elsif ($x eq '+0E+0') {
254 '+0E+0';
255 } else {
256 local($xm, $xe) = split('E',$x);
257 $scale = $div_scale if (!$scale);
258 $scale = length($xm)-1 if ($scale < length($xm)-1);
259 local($gs, $guess) = (1, sprintf("1E%+d", (length($xm)+$xe-1)/2));
260 while ($gs < 2*$scale) {
261 $guess = fmul(fadd($guess,fdiv($x,$guess,$gs*2)),".5");
262 $gs *= 2;
263 }
a5f75d66 264 new Math::BigFloat &fround($guess, $scale);
a0d0e21e 265 }
266}
267
2681;
a5f75d66 269__END__
270
271=head1 NAME
272
273Math::BigFloat - Arbitrary length float math package
274
275=head1 SYNOPSIS
276
a2008d6d 277 use Math::BigFloat;
a5f75d66 278 $f = Math::BigFloat->new($string);
279
280 $f->fadd(NSTR) return NSTR addition
281 $f->fsub(NSTR) return NSTR subtraction
282 $f->fmul(NSTR) return NSTR multiplication
283 $f->fdiv(NSTR[,SCALE]) returns NSTR division to SCALE places
284 $f->fneg() return NSTR negation
285 $f->fabs() return NSTR absolute value
286 $f->fcmp(NSTR) return CODE compare undef,<0,=0,>0
287 $f->fround(SCALE) return NSTR round to SCALE digits
288 $f->ffround(SCALE) return NSTR round at SCALEth place
289 $f->fnorm() return (NSTR) normalize
290 $f->fsqrt([SCALE]) return NSTR sqrt to SCALE places
291
292=head1 DESCRIPTION
293
294All basic math operations are overloaded if you declare your big
295floats as
296
297 $float = new Math::BigFloat "2.123123123123123123123123123123123";
298
299=over 2
300
301=item number format
302
303canonical strings have the form /[+-]\d+E[+-]\d+/ . Input values can
8dcee03e 304have imbedded whitespace.
a5f75d66 305
306=item Error returns 'NaN'
307
308An input parameter was "Not a Number" or divide by zero or sqrt of
309negative number.
310
311=item Division is computed to
312
313C<max($div_scale,length(dividend)+length(divisor))> digits by default.
314Also used for default sqrt scale.
315
316=back
317
318=head1 BUGS
319
320The current version of this module is a preliminary version of the
321real thing that is currently (as of perl5.002) under development.
322
323=head1 AUTHOR
324
325Mark Biggar
326
327=cut