Debian Codegraph @

net/sf/saxon/value/FloatingPointConverter.java

raw symbols SCIP
1 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2 // Copyright (c) 2018 Saxonica Limited.
3 // This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
4 // If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
5 // This Source Code Form is "Incompatible With Secondary Licenses", as defined by the Mozilla Public License, v. 2.0.
6 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
7
8 package net.sf.saxon.value;
9
10 import net.sf.saxon.tree.util.FastStringBuffer;
11
12 import java.math.BigInteger;
13
14 /**
15 * This is a utility class that handles formatting of numbers as strings.
16 * <p>The algorithm for converting a floating point number to a string is taken from Guy L. Steele and
17 * Jon L. White, <i>How to Print Floating-Point Numbers Accurately</i>, ACM SIGPLAN 1990. It is algorithm
18 * (FPP)<sup>2</sup> from that paper. There are three separate implementations of the algorithm:</p>
19 * <ul>
20 * <li>One using long arithmetic and generating non-exponential output representations</li>
21 * <li>One using BigInteger arithmetic and generating non-exponential output representation</li>
22 * <li>One using BigInteger arithmetic and generating exponential output representations</li>
23 * </ul>
24 * <p>The choice of method depends on the value of the number being formatted.</p>
25 * <p>The module contains some residual code (mainly the routine for formatting integers) from the class
26 * AppenderHelper by Jack Shirazi in the O'Reilly book <i>Java Performance Tuning</i>. The floating point routines
27 * in that module were found to be unsuitable, since they used floating point arithmetic which introduces
28 * rounding errors.</p>
29 * <p>There are several reasons for doing this conversion within Saxon, rather than leaving it all to Java.
30 * Firstly, there are differences in the required output format, notably the absence of ".0" when formatting
31 * whole numbers, and the different rules for the range of numbers where exponential notation is used.
32 * Secondly, there are bugs in some Java implementations, for example JDK outputs 0.001 as 0.0010, and
33 * IKVM/GNU gets things very wrong sometimes. Finally, this implementation is faster for "everyday" numbers,
34 * though it is slower for more extreme numbers. It would probably be reasonable to hand over formatting
35 * to the Java platform (at least when running the Sun JDK) for exponents outside the range -7 to +7.</p>
36 */
37
38 public class FloatingPointConverter {
39
40 public static FloatingPointConverter THE_INSTANCE = new FloatingPointConverter();
41
42 private FloatingPointConverter() {
43 }
44
45 /**
46 * char array holding the characters for the string "-Infinity".
47 */
48 private static final char[] NEGATIVE_INFINITY = {'-', 'I', 'N', 'F'};
49 /**
50 * char array holding the characters for the string "Infinity".
51 */
52 private static final char[] POSITIVE_INFINITY = {'I', 'N', 'F'};
53 /**
54 * char array holding the characters for the string "NaN".
55 */
56 private static final char[] NaN = {'N', 'a', 'N'};
57
58 private static final char[] charForDigit = {
59 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'
60 };
61
62 public static final long DOUBLE_SIGN_MASK = 0x8000000000000000L;
63 private static final long doubleExpMask = 0x7ff0000000000000L;
64 private static final int doubleExpShift = 52;
65 private static final int doubleExpBias = 1023;
66 private static final long doubleFractMask = 0xfffffffffffffL;
67 public static final int FLOAT_SIGN_MASK = 0x80000000;
68 private static final int floatExpMask = 0x7f800000;
69 private static final int floatExpShift = 23;
70 private static final int floatExpBias = 127;
71 private static final int floatFractMask = 0x7fffff;
72
73 private static final BigInteger TEN = BigInteger.valueOf(10);
74 private static final BigInteger NINE = BigInteger.valueOf(9);
75
76 /**
77 * Format an integer, appending the string representation of the integer to a string buffer
78 *
79 * @param s the string buffer
80 * @param i the integer to be formatted
81 * @return the supplied string buffer, containing the appended integer
82 */
83
84 public static FastStringBuffer appendInt(FastStringBuffer s, int i) {
85 if (i < 0) {
86 if (i == Integer.MIN_VALUE) {
87 //cannot make this positive due to integer overflow
88 s.append("-2147483648");
89 return s;
90 }
91 s.append('-');
92 i = -i;
93 }
94 int c;
95 if (i < 10) {
96 //one digit
97 s.append(charForDigit[i]);
98 return s;
99 } else if (i < 100) {
100 //two digits
101 s.append(charForDigit[i / 10]);
102 s.append(charForDigit[i % 10]);
103 return s;
104 } else if (i < 1000) {
105 //three digits
106 s.append(charForDigit[i / 100]);
107 s.append(charForDigit[(c = i % 100) / 10]);
108 s.append(charForDigit[c % 10]);
109 return s;
110 } else if (i < 10000) {
111 //four digits
112 s.append(charForDigit[i / 1000]);
113 s.append(charForDigit[(c = i % 1000) / 100]);
114 s.append(charForDigit[(c %= 100) / 10]);
115 s.append(charForDigit[c % 10]);
116 return s;
117 } else if (i < 100000) {
118 //five digits
119 s.append(charForDigit[i / 10000]);
120 s.append(charForDigit[(c = i % 10000) / 1000]);
121 s.append(charForDigit[(c %= 1000) / 100]);
122 s.append(charForDigit[(c %= 100) / 10]);
123 s.append(charForDigit[c % 10]);
124 return s;
125 } else if (i < 1000000) {
126 //six digits
127 s.append(charForDigit[i / 100000]);
128 s.append(charForDigit[(c = i % 100000) / 10000]);
129 s.append(charForDigit[(c %= 10000) / 1000]);
130 s.append(charForDigit[(c %= 1000) / 100]);
131 s.append(charForDigit[(c %= 100) / 10]);
132 s.append(charForDigit[c % 10]);
133 return s;
134 } else if (i < 10000000) {
135 //seven digits
136 s.append(charForDigit[i / 1000000]);
137 s.append(charForDigit[(c = i % 1000000) / 100000]);
138 s.append(charForDigit[(c %= 100000) / 10000]);
139 s.append(charForDigit[(c %= 10000) / 1000]);
140 s.append(charForDigit[(c %= 1000) / 100]);
141 s.append(charForDigit[(c %= 100) / 10]);
142 s.append(charForDigit[c % 10]);
143 return s;
144 } else if (i < 100000000) {
145 //eight digits
146 s.append(charForDigit[i / 10000000]);
147 s.append(charForDigit[(c = i % 10000000) / 1000000]);
148 s.append(charForDigit[(c %= 1000000) / 100000]);
149 s.append(charForDigit[(c %= 100000) / 10000]);
150 s.append(charForDigit[(c %= 10000) / 1000]);
151 s.append(charForDigit[(c %= 1000) / 100]);
152 s.append(charForDigit[(c %= 100) / 10]);
153 s.append(charForDigit[c % 10]);
154 return s;
155 } else if (i < 1000000000) {
156 //nine digits
157 s.append(charForDigit[i / 100000000]);
158 s.append(charForDigit[(c = i % 100000000) / 10000000]);
159 s.append(charForDigit[(c %= 10000000) / 1000000]);
160 s.append(charForDigit[(c %= 1000000) / 100000]);
161 s.append(charForDigit[(c %= 100000) / 10000]);
162 s.append(charForDigit[(c %= 10000) / 1000]);
163 s.append(charForDigit[(c %= 1000) / 100]);
164 s.append(charForDigit[(c %= 100) / 10]);
165 s.append(charForDigit[c % 10]);
166 return s;
167 } else {
168 //ten digits
169 s.append(charForDigit[i / 1000000000]);
170 s.append(charForDigit[(c = i % 1000000000) / 100000000]);
171 s.append(charForDigit[(c %= 100000000) / 10000000]);
172 s.append(charForDigit[(c %= 10000000) / 1000000]);
173 s.append(charForDigit[(c %= 1000000) / 100000]);
174 s.append(charForDigit[(c %= 100000) / 10000]);
175 s.append(charForDigit[(c %= 10000) / 1000]);
176 s.append(charForDigit[(c %= 1000) / 100]);
177 s.append(charForDigit[(c %= 100) / 10]);
178 s.append(charForDigit[c % 10]);
179 return s;
180 }
181 }
182
183 /**
184 * Implementation of the (FPP)2 algorithm from Steele and White, for doubles in the range
185 * 0.01 to 1000000, and floats in the range 0.000001 to 1000000.
186 * In this range (a) XPath requires that the output should not be in exponential
187 * notation, and (b) the arithmetic can be handled using longs rather than BigIntegers
188 *
189 * @param sb the string buffer to which the formatted result is to be appended
190 * @param e the exponent of the floating point number
191 * @param f the fraction part of the floating point number, such that the "real" value of the
192 * number is f * 2^(e-p), with p&gt;=0 and 0 lt f lt 2^p
193 * @param p the precision
194 */
195
196 private static void fppfpp(FastStringBuffer sb, int e, long f, int p) {
197 long R = f << Math.max(e - p, 0);
198 long S = 1L << Math.max(0, -(e - p));
199 long Mminus = 1L << Math.max(e - p, 0);
200 long Mplus = Mminus;
201 boolean initial = true;
202
203 // simpleFixup
204
205 if (f == 1L << (p - 1)) {
206 Mplus = Mplus << 1;
207 R = R << 1;
208 S = S << 1;
209 }
210 int k = 0;
211 while (R < (S + 9) / 10) { // (S+9)/10 == ceiling(S/10)
212 k--;
213 R = R * 10;
214 Mminus = Mminus * 10;
215 Mplus = Mplus * 10;
216 }
217 while (2 * R + Mplus >= 2 * S) {
218 S = S * 10;
219 k++;
220 }
221
222 for (int z = k; z < 0; z++) {
223 if (initial) {
224 sb.append("0.");
225 }
226 initial = false;
227 sb.append('0');
228 }
229
230 // end simpleFixup
231
232 //int H = k-1;
233
234 boolean low;
235 boolean high;
236 int U;
237 while (true) {
238 k--;
239 long R10 = R * 10;
240 U = (int) (R10 / S);
241 R = R10 - (U * S); // = R*10 % S, but faster - saves a division
242 Mminus = Mminus * 10;
243 Mplus = Mplus * 10;
244 low = 2 * R < Mminus;
245 high = 2 * R > 2 * S - Mplus;
246 if (low || high) break;
247 if (k == -1) {
248 if (initial) {
249 sb.append('0');
250 }
251 sb.append('.');
252 }
253 sb.append(charForDigit[U]);
254 initial = false;
255 }
256 if (high && (!low || 2 * R > S)) {
257 U++;
258 }
259 if (k == -1) {
260 if (initial) {
261 sb.append('0');
262 }
263 sb.append('.');
264 }
265 sb.append(charForDigit[U]);
266 for (int z = 0; z < k; z++) {
267 sb.append('0');
268 }
269 }
270
271 /**
272 * Implementation of the (FPP)2 algorithm from Steele and White, for doubles in the range
273 * 0.000001 to 0.01. In this range XPath requires that the output should not be in exponential
274 * notation, but the scale factors are large enough to exceed the capacity of long arithmetic.
275 *
276 * @param sb the string buffer to which the formatted result is to be appended
277 * @param e the exponent of the floating point number
278 * @param f the fraction part of the floating point number, such that the "real" value of the
279 * number is f * 2^(e-p), with p&gt;=0 and 0 lt f lt 2^p
280 * @param p the precision
281 */
282
283 private static void fppfppBig(FastStringBuffer sb, int e, long f, int p) {
284 //long R = f << Math.max(e-p, 0);
285 BigInteger R = BigInteger.valueOf(f).shiftLeft(Math.max(e - p, 0));
286
287 //long S = 1L << Math.max(0, -(e-p));
288 BigInteger S = BigInteger.ONE.shiftLeft(Math.max(0, -(e - p)));
289
290 //long Mminus = 1 << Math.max(e-p, 0);
291 BigInteger Mminus = BigInteger.ONE.shiftLeft(Math.max(e - p, 0));
292
293 //long Mplus = Mminus;
294 BigInteger Mplus = Mminus;
295
296 boolean initial = true;
297
298 // simpleFixup
299
300 if (f == 1L << (p - 1)) {
301 Mplus = Mplus.shiftLeft(1);
302 R = R.shiftLeft(1);
303 S = S.shiftLeft(1);
304 }
305 int k = 0;
306 while (R.compareTo(S.add(NINE).divide(TEN)) < 0) { // (S+9)/10 == ceiling(S/10)
307 k--;
308 R = R.multiply(TEN);
309 Mminus = Mminus.multiply(TEN);
310 Mplus = Mplus.multiply(TEN);
311 }
312 while (R.shiftLeft(1).add(Mplus).compareTo(S.shiftLeft(1)) >= 0) {
313 S = S.multiply(TEN);
314 k++;
315 }
316
317 for (int z = k; z < 0; z++) {
318 if (initial) {
319 sb.append("0.");
320 }
321 initial = false;
322 sb.append('0');
323 }
324
325 // end simpleFixup
326
327 //int H = k-1;
328
329 boolean low;
330 boolean high;
331 int U;
332 while (true) {
333 k--;
334 BigInteger R10 = R.multiply(TEN);
335 U = R10.divide(S).intValue();
336 R = R10.mod(S);
337 Mminus = Mminus.multiply(TEN);
338 Mplus = Mplus.multiply(TEN);
339 BigInteger R2 = R.shiftLeft(1);
340 low = R2.compareTo(Mminus) < 0;
341 high = R2.compareTo(S.shiftLeft(1).subtract(Mplus)) > 0;
342 if (low || high) break;
343 if (k == -1) {
344 if (initial) {
345 sb.append('0');
346 }
347 sb.append('.');
348 }
349 sb.append(charForDigit[U]);
350 initial = false;
351 }
352 if (high && (!low || R.shiftLeft(1).compareTo(S) > 0)) {
353 U++;
354 }
355 if (k == -1) {
356 if (initial) {
357 sb.append('0');
358 }
359 sb.append('.');
360 }
361 sb.append(charForDigit[U]);
362 for (int z = 0; z < k; z++) {
363 sb.append('0');
364 }
365 }
366
367
368 /**
369 * Implementation of the (FPP)2 algorithm from Steele and White, for numbers outside the range
370 * 0.000001 to 1000000. In this range XPath requires that the output should be in exponential
371 * notation
372 *
373 * @param sb the string buffer to which the formatted result is to be appended
374 * @param e the exponent of the floating point number
375 * @param f the fraction part of the floating point number, such that the "real" value of the
376 * number is f * 2^(e-p), with p&gt;=0 and 0 lt f lt 2^p
377 * @param p the precision
378 */
379
380 private static void fppfppExponential(FastStringBuffer sb, int e, long f, int p) {
381 //long R = f << Math.max(e-p, 0);
382 BigInteger R = BigInteger.valueOf(f).shiftLeft(Math.max(e - p, 0));
383
384 //long S = 1L << Math.max(0, -(e-p));
385 BigInteger S = BigInteger.ONE.shiftLeft(Math.max(0, -(e - p)));
386
387 //long Mminus = 1 << Math.max(e-p, 0);
388 BigInteger Mminus = BigInteger.ONE.shiftLeft(Math.max(e - p, 0));
389
390 //long Mplus = Mminus;
391 BigInteger Mplus = Mminus;
392
393 boolean initial = true;
394 boolean doneDot = false;
395
396 // simpleFixup
397
398 if (f == 1L << (p - 1)) {
399 Mplus = Mplus.shiftLeft(1);
400 R = R.shiftLeft(1);
401 S = S.shiftLeft(1);
402 }
403 int k = 0;
404 while (R.compareTo(S.add(NINE).divide(TEN)) < 0) { // (S+9)/10 == ceiling(S/10)
405 k--;
406 R = R.multiply(TEN);
407 Mminus = Mminus.multiply(TEN);
408 Mplus = Mplus.multiply(TEN);
409 }
410 while (R.shiftLeft(1).add(Mplus).compareTo(S.shiftLeft(1)) >= 0) {
411 S = S.multiply(TEN);
412 k++;
413 }
414
415 // end simpleFixup
416
417 int H = k - 1;
418
419 boolean low;
420 boolean high;
421 int U;
422 while (true) {
423 k--;
424 BigInteger R10 = R.multiply(TEN);
425 U = R10.divide(S).intValue();
426 R = R10.mod(S);
427 Mminus = Mminus.multiply(TEN);
428 Mplus = Mplus.multiply(TEN);
429 BigInteger R2 = R.shiftLeft(1);
430 low = R2.compareTo(Mminus) < 0;
431 high = R2.compareTo(S.shiftLeft(1).subtract(Mplus)) > 0;
432 if (low || high) break;
433
434 sb.append(charForDigit[U]);
435 if (initial) {
436 sb.append('.');
437 doneDot = true;
438 }
439 initial = false;
440 }
441 if (high && (!low || R.shiftLeft(1).compareTo(S) > 0)) {
442 U++;
443 }
444 sb.append(charForDigit[U]);
445
446 if (!doneDot) {
447 sb.append(".0");
448 }
449 sb.append('E');
450 appendInt(sb, H);
451
452 }
453
454 /**
455 * Append a string representation of a double value to a string buffer
456 *
457 * @param s the string buffer to which the result will be appended
458 * @param d the double to be formatted
459 * @return the original string buffer, now containing the string representation of the supplied double
460 */
461
462 public static FastStringBuffer appendDouble(FastStringBuffer s, double d, boolean forceExponential) {
463 if (d == Double.NEGATIVE_INFINITY) {
464 s.append(NEGATIVE_INFINITY);
465 } else if (d == Double.POSITIVE_INFINITY) {
466 s.append(POSITIVE_INFINITY);
467 } else if (d != d) {
468 s.append(NaN);
469 } else if (d == 0.0) {
470 if ((Double.doubleToLongBits(d) & DOUBLE_SIGN_MASK) != 0) {
471 s.append('-');
472 }
473 s.append('0');
474 if (forceExponential) {
475 s.append(".0E0");
476 }
477 } else if (d == Double.MAX_VALUE) {
478 s.append("1.7976931348623157E308");
479 } else if (d == -Double.MAX_VALUE) {
480 s.append("-1.7976931348623157E308");
481 } else if (d == Double.MIN_VALUE) {
482 s.append("4.9E-324");
483 } else if (d == -Double.MIN_VALUE) {
484 s.append("-4.9E-324");
485 } else {
486 if (d < 0) {
487 s.append('-');
488 d = -d;
489 }
490 long bits = Double.doubleToLongBits(d);
491 long fraction = (1L << 52) | (bits & doubleFractMask);
492 long rawExp = (bits & doubleExpMask) >> doubleExpShift;
493 int exp = (int) rawExp - doubleExpBias;
494 if (rawExp == 0) {
495 // don't know how to handle this currently: hand it over to Java to deal with
496 s.append(Double.toString(d));
497 return s;
498 }
499 if (forceExponential || (d >= 1000000 || d < 0.000001)) {
500 fppfppExponential(s, exp, fraction, 52);
501 } else {
502 if (d <= 0.01) {
503 fppfppBig(s, exp, fraction, 52);
504 } else {
505 fppfpp(s, exp, fraction, 52);
506 }
507 }
508
509 // test code
510 // try {
511 // if (Double.parseDouble(s.toString()) != value) {
512 // System.err.println("*** Round-trip failed: input " + value +
513 // '(' + Double.doubleToLongBits(value) + ')' +
514 // " != output " + s.toString() +
515 // '(' + Double.doubleToLongBits(Double.parseDouble(s.toString())) + ')' );
516 // }
517 // } catch (NumberFormatException e) {
518 // System.err.println("*** Bad float " + s.toString() + " for input " + value);
519 // }
520 }
521 return s;
522 }
523
524 /**
525 * Append a string representation of a float value to a string buffer
526 *
527 * @param s the string buffer to which the result will be appended
528 * @param f the float to be formatted
529 * @param forceExponential forces exponential notation if set (if not set, exponential notation
530 * is used only for values outside the range 1e-6 to 1e+6)
531 * @return the original string buffer, now containing the string representation of the supplied float
532 */
533
534 /*@NotNull*/
535 public static FastStringBuffer appendFloat(FastStringBuffer s, float f, boolean forceExponential) {
536 if (f == Float.NEGATIVE_INFINITY) {
537 s.append(NEGATIVE_INFINITY);
538 } else if (f == Float.POSITIVE_INFINITY) {
539 s.append(POSITIVE_INFINITY);
540 } else if (f != f) {
541 s.append(NaN);
542 } else if (f == 0.0) {
543 if ((Float.floatToIntBits(f) & FLOAT_SIGN_MASK) != 0) {
544 s.append('-');
545 }
546 s.append('0');
547 } else if (f == Float.MAX_VALUE) {
548 s.append("3.4028235E38");
549 } else if (f == -Float.MAX_VALUE) {
550 s.append("-3.4028235E38");
551 } else if (f == Float.MIN_VALUE) {
552 s.append("1.4E-45");
553 } else if (f == -Float.MIN_VALUE) {
554 s.append("-1.4E-45");
555 } else {
556 if (f < 0) {
557 s.append('-');
558 f = -f;
559 }
560 int bits = Float.floatToIntBits(f);
561 int fraction = (1 << 23) | (bits & floatFractMask);
562 int rawExp = ((bits & floatExpMask) >> floatExpShift);
563 int exp = rawExp - floatExpBias;
564 int precision = 23;
565 if (rawExp == 0) {
566 // don't know how to handle this currently: hand it over to Java to deal with
567 s.append(Float.toString(f));
568 return s;
569 }
570 if (forceExponential || (f >= 1000000 || f < 0.000001F)) {
571 fppfppExponential(s, exp, fraction, precision);
572 } else {
573 fppfpp(s, exp, fraction, precision);
574 }
575 }
576 return s;
577 }
578
579
580 // public static void main(String[] args) {
581 // if (args.length > 0 && args[0].equals("F")) {
582 // if (args.length == 2) {
583 // StringTokenizer tok = new StringTokenizer(args[1], ",");
584 // while (tok.hasMoreElements()) {
585 // String input = tok.nextToken();
586 // float f = Float.parseFloat(input);
587 // FastStringBuffer sb = new FastStringBuffer(20);
588 // appendFloat(sb, f);
589 // System.err.println("input: " + input + " output: " + sb.toString() + " java: " + f);
590 // }
591 // } else {
592 // Random gen = new Random();
593 // for (int i=1; i<1000; i++) {
594 // int p=gen.nextInt(999*i*i);
595 // int q=gen.nextInt(999*i*i);
596 // String input = (p + "." + q);
597 // float f = Float.parseFloat(input);
598 // FastStringBuffer sb = new FastStringBuffer(20);
599 // appendFloat(sb, f);
600 // System.err.println("input: " + input + " output: " + sb.toString() + " java: " + f);
601 // }
602 // }
603 // } else {
604 // if (args.length == 2) {
605 // StringTokenizer tok = new StringTokenizer(args[1], ",");
606 // while (tok.hasMoreElements()) {
607 // String input = tok.nextToken();
608 // double f = Double.parseDouble(input);
609 // FastStringBuffer sb = new FastStringBuffer(20);
610 // appendDouble(sb, f);
611 // System.err.println("input: " + input + " output: " + sb.toString() + " java: " + f);
612 // }
613 // } else {
614 // long start = System.currentTimeMillis();
615 // Random gen = new Random();
616 // for (int i=1; i<100000; i++) {
617 // //int p=gen.nextInt(999*i*i);
618 // int q=gen.nextInt(999*i);
619 // //String input = (p + "." + q);
620 // String input = "0.000" + q;
621 // double f = Double.parseDouble(input);
622 // FastStringBuffer sb = new FastStringBuffer(20);
623 // appendDouble(sb, f);
624 // //System.err.println("input: " + input + " output: " + sb.toString() + " java: " + f);
625 // }
626 // System.err.println("** elapsed time " + (System.currentTimeMillis() - start));
627 // }
628 // }
629 // }
630
631
632 }
633
634