Commit | Line | Data |
a0d0e21e |
1 | package Math::BigFloat; |
2 | |
3 | use Math::BigInt; |
4 | |
5 | use Exporter; # just for use to be happy |
6 | @ISA = (Exporter); |
7 | |
a5f75d66 |
8 | use 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 | |
23 | qw( |
24 | "" stringify |
25 | 0+ numify) # Order of arguments unsignificant |
a5f75d66 |
26 | ; |
a0d0e21e |
27 | |
28 | sub 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 | } |
34 | sub numify { 0 + "${$_[0]}" } # Not needed, additional overhead |
35 | # comparing to direct compilation based on |
36 | # stringify |
37 | sub stringify { |
38 | my $n = ${$_[0]}; |
39 | |
40 | $n =~ s/^\+//; |
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 | } |
55 | |
56 | # 1 while $n =~ s/(.*\d)(\d\d\d)/$1,$2/; |
57 | |
58 | return $n; |
59 | } |
60 | |
a0d0e21e |
61 | $div_scale = 40; |
62 | |
63 | # Rounding modes one of 'even', 'odd', '+inf', '-inf', 'zero' or 'trunc'. |
64 | |
65 | $rnd_mode = 'even'; |
66 | |
67 | sub fadd; sub fsub; sub fmul; sub fdiv; |
68 | sub fneg; sub fabs; sub fcmp; |
69 | sub fround; sub ffround; |
70 | sub fnorm; sub fsqrt; |
71 | |
a0d0e21e |
72 | # Convert a number to canonical string form. |
73 | # Takes something that looks like a number and converts it to |
74 | # the form /^[+-]\d+E[+-]\d+$/. |
75 | sub fnorm { #(string) return fnum_str |
76 | local($_) = @_; |
77 | s/\s+//g; # strip white space |
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 |
86 | sub 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 |
102 | sub 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 |
110 | sub fabs { #(fnum_str) return fnum_str |
111 | local($_) = fnorm($_[$[]); |
112 | s/^-/+/; # mash sign |
113 | $_; |
114 | } |
115 | |
116 | # multiplication |
117 | sub 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 |
129 | sub 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 |
142 | sub 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 |
149 | sub 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); |
161 | &norm(&round(Math::BigInt::bdiv($xm.('0' x $scale),$ym),$ym), |
162 | $xe-$ye-$scale); |
163 | } |
164 | } |
a5f75d66 |
165 | |
a0d0e21e |
166 | # round int $q based on fraction $r/$base using $rnd_mode |
167 | sub round { #(int_str, int_str, int_str) return int_str |
168 | local($q,$r,$base) = @_; |
169 | if ($q eq 'NaN' || $r eq 'NaN') { |
170 | 'NaN'; |
171 | } elsif ($rnd_mode eq 'trunc') { |
172 | $q; # just truncate |
173 | } else { |
174 | local($cmp) = Math::BigInt::bcmp(Math::BigInt::bmul($r,'+2'),$base); |
175 | if ( $cmp < 0 || |
176 | ($cmp == 0 && |
177 | ( $rnd_mode eq 'zero' || |
178 | ($rnd_mode eq '-inf' && (substr($q,$[,1) eq '+')) || |
179 | ($rnd_mode eq '+inf' && (substr($q,$[,1) eq '-')) || |
180 | ($rnd_mode eq 'even' && $q =~ /[24680]$/) || |
181 | ($rnd_mode eq 'odd' && $q =~ /[13579]$/) )) ) { |
182 | $q; # round down |
183 | } else { |
184 | Math::BigInt::badd($q, ((substr($q,$[,1) eq '-') ? '-1' : '+1')); |
185 | # round up |
186 | } |
187 | } |
188 | } |
189 | |
190 | # round the mantissa of $x to $scale digits |
191 | sub fround { #(fnum_str, scale) return fnum_str |
192 | local($x,$scale) = (fnorm($_[$[]),$_[$[+1]); |
193 | if ($x eq 'NaN' || $scale <= 0) { |
194 | $x; |
195 | } else { |
196 | local($xm,$xe) = split('E',$x); |
197 | if (length($xm)-1 <= $scale) { |
198 | $x; |
199 | } else { |
200 | &norm(&round(substr($xm,$[,$scale+1), |
201 | "+0".substr($xm,$[+$scale+1,1),"+10"), |
202 | $xe+length($xm)-$scale-1); |
203 | } |
204 | } |
205 | } |
a5f75d66 |
206 | |
a0d0e21e |
207 | # round $x at the 10 to the $scale digit place |
208 | sub ffround { #(fnum_str, scale) return fnum_str |
209 | local($x,$scale) = (fnorm($_[$[]),$_[$[+1]); |
210 | if ($x eq 'NaN') { |
211 | 'NaN'; |
212 | } else { |
213 | local($xm,$xe) = split('E',$x); |
214 | if ($xe >= $scale) { |
215 | $x; |
216 | } else { |
217 | $xe = length($xm)+$xe-$scale; |
218 | if ($xe < 1) { |
219 | '+0E+0'; |
220 | } elsif ($xe == 1) { |
221 | &norm(&round('+0',"+0".substr($xm,$[+1,1),"+10"), $scale); |
222 | } else { |
223 | &norm(&round(substr($xm,$[,$xe), |
224 | "+0".substr($xm,$[+$xe,1),"+10"), $scale); |
225 | } |
226 | } |
227 | } |
228 | } |
229 | |
230 | # compare 2 values returns one of undef, <0, =0, >0 |
231 | # returns undef if either or both input value are not numbers |
232 | sub fcmp #(fnum_str, fnum_str) return cond_code |
233 | { |
234 | local($x, $y) = (fnorm($_[$[]),fnorm($_[$[+1])); |
235 | if ($x eq "NaN" || $y eq "NaN") { |
236 | undef; |
237 | } else { |
238 | ord($y) <=> ord($x) |
239 | || |
240 | ( local($xm,$xe,$ym,$ye) = split('E', $x."E$y"), |
241 | (($xe <=> $ye) * (substr($x,$[,1).'1') |
242 | || Math::BigInt::cmp($xm,$ym)) |
243 | ); |
244 | } |
245 | } |
a5f75d66 |
246 | |
a0d0e21e |
247 | # square root by Newtons method. |
248 | sub fsqrt { #(fnum_str[, scale]) return fnum_str |
249 | local($x, $scale) = (fnorm($_[$[]), $_[$[+1]); |
250 | if ($x eq 'NaN' || $x =~ /^-/) { |
251 | 'NaN'; |
252 | } elsif ($x eq '+0E+0') { |
253 | '+0E+0'; |
254 | } else { |
255 | local($xm, $xe) = split('E',$x); |
256 | $scale = $div_scale if (!$scale); |
257 | $scale = length($xm)-1 if ($scale < length($xm)-1); |
258 | local($gs, $guess) = (1, sprintf("1E%+d", (length($xm)+$xe-1)/2)); |
259 | while ($gs < 2*$scale) { |
260 | $guess = fmul(fadd($guess,fdiv($x,$guess,$gs*2)),".5"); |
261 | $gs *= 2; |
262 | } |
a5f75d66 |
263 | new Math::BigFloat &fround($guess, $scale); |
a0d0e21e |
264 | } |
265 | } |
266 | |
267 | 1; |
a5f75d66 |
268 | __END__ |
269 | |
270 | =head1 NAME |
271 | |
272 | Math::BigFloat - Arbitrary length float math package |
273 | |
274 | =head1 SYNOPSIS |
275 | |
276 | use Math::BogFloat; |
277 | $f = Math::BigFloat->new($string); |
278 | |
279 | $f->fadd(NSTR) return NSTR addition |
280 | $f->fsub(NSTR) return NSTR subtraction |
281 | $f->fmul(NSTR) return NSTR multiplication |
282 | $f->fdiv(NSTR[,SCALE]) returns NSTR division to SCALE places |
283 | $f->fneg() return NSTR negation |
284 | $f->fabs() return NSTR absolute value |
285 | $f->fcmp(NSTR) return CODE compare undef,<0,=0,>0 |
286 | $f->fround(SCALE) return NSTR round to SCALE digits |
287 | $f->ffround(SCALE) return NSTR round at SCALEth place |
288 | $f->fnorm() return (NSTR) normalize |
289 | $f->fsqrt([SCALE]) return NSTR sqrt to SCALE places |
290 | |
291 | =head1 DESCRIPTION |
292 | |
293 | All basic math operations are overloaded if you declare your big |
294 | floats as |
295 | |
296 | $float = new Math::BigFloat "2.123123123123123123123123123123123"; |
297 | |
298 | =over 2 |
299 | |
300 | =item number format |
301 | |
302 | canonical strings have the form /[+-]\d+E[+-]\d+/ . Input values can |
303 | have inbedded whitespace. |
304 | |
305 | =item Error returns 'NaN' |
306 | |
307 | An input parameter was "Not a Number" or divide by zero or sqrt of |
308 | negative number. |
309 | |
310 | =item Division is computed to |
311 | |
312 | C<max($div_scale,length(dividend)+length(divisor))> digits by default. |
313 | Also used for default sqrt scale. |
314 | |
315 | =back |
316 | |
317 | =head1 BUGS |
318 | |
319 | The current version of this module is a preliminary version of the |
320 | real thing that is currently (as of perl5.002) under development. |
321 | |
322 | =head1 AUTHOR |
323 | |
324 | Mark Biggar |
325 | |
326 | =cut |