make reset() behave with high-bit characters
[p5sagit/p5-mst-13.2.git] / lib / bigfloat.pl
CommitLineData
5303340c 1package bigfloat;
2require "bigint.pl";
5303340c 3# Arbitrary length float math package
4#
68decaef 5# by Mark Biggar
6#
5303340c 7# number format
8# canonical strings have the form /[+-]\d+E[+-]\d+/
5d7098d5 9# Input values can have embedded whitespace
5303340c 10# Error returns
11# 'NaN' An input parameter was "Not a Number" or
12# divide by zero or sqrt of negative number
13# Division is computed to
79072805 14# max($div_scale,length(dividend)+length(divisor))
5303340c 15# digits by default.
16# Also used for default sqrt scale
17
18$div_scale = 40;
19
20# Rounding modes one of 'even', 'odd', '+inf', '-inf', 'zero' or 'trunc'.
21
22$rnd_mode = 'even';
23
24# bigfloat routines
25#
26# fadd(NSTR, NSTR) return NSTR addition
27# fsub(NSTR, NSTR) return NSTR subtraction
28# fmul(NSTR, NSTR) return NSTR multiplication
29# fdiv(NSTR, NSTR[,SCALE]) returns NSTR division to SCALE places
30# fneg(NSTR) return NSTR negation
31# fabs(NSTR) return NSTR absolute value
32# fcmp(NSTR,NSTR) return CODE compare undef,<0,=0,>0
33# fround(NSTR, SCALE) return NSTR round to SCALE digits
34# ffround(NSTR, SCALE) return NSTR round at SCALEth place
35# fnorm(NSTR) return (NSTR) normalize
36# fsqrt(NSTR[, SCALE]) return NSTR sqrt to SCALE places
37\f
38# Convert a number to canonical string form.
39# Takes something that looks like a number and converts it to
40# the form /^[+-]\d+E[+-]\d+$/.
41sub main'fnorm { #(string) return fnum_str
42 local($_) = @_;
43 s/\s+//g; # strip white space
afea815c 44 if (/^([+-]?)(\d*)(\.(\d*))?([Ee]([+-]?\d+))?$/
45 && ($2 ne '' || defined($4))) {
46 my $x = defined($4) ? $4 : '';
47 &norm(($1 ? "$1$2$x" : "+$2$x"), (($x ne '') ? $6-length($x) : $6));
5303340c 48 } else {
49 'NaN';
50 }
51}
52
53# normalize number -- for internal use
54sub norm { #(mantissa, exponent) return fnum_str
55 local($_, $exp) = @_;
56 if ($_ eq 'NaN') {
57 'NaN';
58 } else {
59 s/^([+-])0+/$1/; # strip leading zeros
60 if (length($_) == 1) {
61 '+0E+0';
62 } else {
63 $exp += length($1) if (s/(0+)$//); # strip trailing zeros
64 sprintf("%sE%+ld", $_, $exp);
65 }
66 }
67}
68
69# negation
70sub main'fneg { #(fnum_str) return fnum_str
79072805 71 local($_) = &'fnorm($_[$[]);
e334a159 72 vec($_,0,8) ^= ord('+') ^ ord('-') unless $_ eq '+0E+0'; # flip sign
68decaef 73 s/^H/N/;
5303340c 74 $_;
75}
76
77# absolute value
78sub main'fabs { #(fnum_str) return fnum_str
79072805 79 local($_) = &'fnorm($_[$[]);
68decaef 80 s/^-/+/; # mash sign
5303340c 81 $_;
82}
83
84# multiplication
85sub main'fmul { #(fnum_str, fnum_str) return fnum_str
79072805 86 local($x,$y) = (&'fnorm($_[$[]),&'fnorm($_[$[+1]));
5303340c 87 if ($x eq 'NaN' || $y eq 'NaN') {
88 'NaN';
89 } else {
90 local($xm,$xe) = split('E',$x);
91 local($ym,$ye) = split('E',$y);
92 &norm(&'bmul($xm,$ym),$xe+$ye);
93 }
94}
95\f
96# addition
97sub main'fadd { #(fnum_str, fnum_str) return fnum_str
79072805 98 local($x,$y) = (&'fnorm($_[$[]),&'fnorm($_[$[+1]));
5303340c 99 if ($x eq 'NaN' || $y eq 'NaN') {
100 'NaN';
101 } else {
102 local($xm,$xe) = split('E',$x);
103 local($ym,$ye) = split('E',$y);
104 ($xm,$xe,$ym,$ye) = ($ym,$ye,$xm,$xe) if ($xe < $ye);
105 &norm(&'badd($ym,$xm.('0' x ($xe-$ye))),$ye);
106 }
107}
108
109# subtraction
110sub main'fsub { #(fnum_str, fnum_str) return fnum_str
79072805 111 &'fadd($_[$[],&'fneg($_[$[+1]));
5303340c 112}
113
114# division
115# args are dividend, divisor, scale (optional)
116# result has at most max(scale, length(dividend), length(divisor)) digits
117sub main'fdiv #(fnum_str, fnum_str[,scale]) return fnum_str
118{
79072805 119 local($x,$y,$scale) = (&'fnorm($_[$[]),&'fnorm($_[$[+1]),$_[$[+2]);
5303340c 120 if ($x eq 'NaN' || $y eq 'NaN' || $y eq '+0E+0') {
121 'NaN';
122 } else {
123 local($xm,$xe) = split('E',$x);
124 local($ym,$ye) = split('E',$y);
125 $scale = $div_scale if (!$scale);
126 $scale = length($xm)-1 if (length($xm)-1 > $scale);
127 $scale = length($ym)-1 if (length($ym)-1 > $scale);
128 $scale = $scale + length($ym) - length($xm);
5d7098d5 129 &norm(&round(&'bdiv($xm.('0' x $scale),$ym),&'babs($ym)),
5303340c 130 $xe-$ye-$scale);
131 }
132}
133\f
134# round int $q based on fraction $r/$base using $rnd_mode
135sub round { #(int_str, int_str, int_str) return int_str
136 local($q,$r,$base) = @_;
137 if ($q eq 'NaN' || $r eq 'NaN') {
138 'NaN';
139 } elsif ($rnd_mode eq 'trunc') {
140 $q; # just truncate
141 } else {
142 local($cmp) = &'bcmp(&'bmul($r,'+2'),$base);
143 if ( $cmp < 0 ||
144 ($cmp == 0 &&
145 ( $rnd_mode eq 'zero' ||
79072805 146 ($rnd_mode eq '-inf' && (substr($q,$[,1) eq '+')) ||
147 ($rnd_mode eq '+inf' && (substr($q,$[,1) eq '-')) ||
5303340c 148 ($rnd_mode eq 'even' && $q =~ /[24680]$/) ||
149 ($rnd_mode eq 'odd' && $q =~ /[13579]$/) )) ) {
150 $q; # round down
151 } else {
79072805 152 &'badd($q, ((substr($q,$[,1) eq '-') ? '-1' : '+1'));
5303340c 153 # round up
154 }
155 }
156}
157
158# round the mantissa of $x to $scale digits
159sub main'fround { #(fnum_str, scale) return fnum_str
79072805 160 local($x,$scale) = (&'fnorm($_[$[]),$_[$[+1]);
5303340c 161 if ($x eq 'NaN' || $scale <= 0) {
162 $x;
163 } else {
164 local($xm,$xe) = split('E',$x);
165 if (length($xm)-1 <= $scale) {
166 $x;
167 } else {
79072805 168 &norm(&round(substr($xm,$[,$scale+1),
169 "+0".substr($xm,$[+$scale+1,1),"+10"),
5303340c 170 $xe+length($xm)-$scale-1);
171 }
172 }
173}
174\f
175# round $x at the 10 to the $scale digit place
176sub main'ffround { #(fnum_str, scale) return fnum_str
79072805 177 local($x,$scale) = (&'fnorm($_[$[]),$_[$[+1]);
5303340c 178 if ($x eq 'NaN') {
179 'NaN';
180 } else {
181 local($xm,$xe) = split('E',$x);
182 if ($xe >= $scale) {
183 $x;
184 } else {
185 $xe = length($xm)+$xe-$scale;
186 if ($xe < 1) {
187 '+0E+0';
188 } elsif ($xe == 1) {
5d7098d5 189 # The first substr preserves the sign, which means that
190 # we'll pass a non-normalized "-0" to &round when rounding
191 # -0.006 (for example), purely so that &round won't lose
192 # the sign.
193 &norm(&round(substr($xm,$[,1).'0',
194 "+0".substr($xm,$[+1,1),"+10"), $scale);
5303340c 195 } else {
79072805 196 &norm(&round(substr($xm,$[,$xe),
197 "+0".substr($xm,$[+$xe,1),"+10"), $scale);
5303340c 198 }
199 }
200 }
201}
202
203# compare 2 values returns one of undef, <0, =0, >0
204# returns undef if either or both input value are not numbers
205sub main'fcmp #(fnum_str, fnum_str) return cond_code
206{
79072805 207 local($x, $y) = (&'fnorm($_[$[]),&'fnorm($_[$[+1]));
5303340c 208 if ($x eq "NaN" || $y eq "NaN") {
209 undef;
5303340c 210 } else {
68decaef 211 ord($y) <=> ord($x)
212 ||
213 ( local($xm,$xe,$ym,$ye) = split('E', $x."E$y"),
79072805 214 (($xe <=> $ye) * (substr($x,$[,1).'1')
68decaef 215 || &bigint'cmp($xm,$ym))
216 );
5303340c 217 }
218}
219\f
220# square root by Newtons method.
221sub main'fsqrt { #(fnum_str[, scale]) return fnum_str
79072805 222 local($x, $scale) = (&'fnorm($_[$[]), $_[$[+1]);
5303340c 223 if ($x eq 'NaN' || $x =~ /^-/) {
224 'NaN';
225 } elsif ($x eq '+0E+0') {
226 '+0E+0';
227 } else {
228 local($xm, $xe) = split('E',$x);
229 $scale = $div_scale if (!$scale);
230 $scale = length($xm)-1 if ($scale < length($xm)-1);
231 local($gs, $guess) = (1, sprintf("1E%+d", (length($xm)+$xe-1)/2));
232 while ($gs < 2*$scale) {
233 $guess = &'fmul(&'fadd($guess,&'fdiv($x,$guess,$gs*2)),".5");
234 $gs *= 2;
235 }
236 &'fround($guess, $scale);
237 }
238}
239
2401;