1 ------------------------------------------------------------------------------
3 -- GNAT RUN-TIME COMPONENTS --
5 -- A D A . T E X T _ I O . F I X E D _ I O --
9 -- Copyright (C) 1992-2009, Free Software Foundation, Inc. --
11 -- GNAT is free software; you can redistribute it and/or modify it under --
12 -- terms of the GNU General Public License as published by the Free Soft- --
13 -- ware Foundation; either version 3, or (at your option) any later ver- --
14 -- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
15 -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
16 -- or FITNESS FOR A PARTICULAR PURPOSE. --
18 -- As a special exception under Section 7 of GPL version 3, you are granted --
19 -- additional permissions described in the GCC Runtime Library Exception, --
20 -- version 3.1, as published by the Free Software Foundation. --
22 -- You should have received a copy of the GNU General Public License and --
23 -- a copy of the GCC Runtime Library Exception along with this program; --
24 -- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see --
25 -- <http://www.gnu.org/licenses/>. --
27 -- GNAT was originally developed by the GNAT team at New York University. --
28 -- Extensive contributions were provided by Ada Core Technologies Inc. --
30 ------------------------------------------------------------------------------
35 -- The following documents implementation details of the fixed point
36 -- input/output routines in the GNAT run time. The first part describes
37 -- general properties of fixed point types as defined by the Ada 95 standard,
38 -- including the Information Systems Annex.
40 -- Subsequently these are reduced to implementation constraints and the impact
41 -- of these constraints on a few possible approaches to I/O are given.
42 -- Based on this analysis, a specific implementation is selected for use in
43 -- the GNAT run time. Finally, the chosen algorithm is analyzed numerically in
44 -- order to provide user-level documentation on limits for range and precision
45 -- of fixed point types as well as accuracy of input/output conversions.
47 -- -------------------------------------------
48 -- - General Properties of Fixed Point Types -
49 -- -------------------------------------------
51 -- Operations on fixed point values, other than input and output, are not
52 -- important for the purposes of this document. Only the set of values that a
53 -- fixed point type can represent and the input and output operations are
59 -- Set set of values of a fixed point type comprise the integral
60 -- multiples of a number called the small of the type. The small can
61 -- either be a power of ten, a power of two or (if the implementation
62 -- allows) an arbitrary strictly positive real value.
64 -- Implementations need to support fixed-point types with a precision
65 -- of at least 24 bits, and (in order to comply with the Information
66 -- Systems Annex) decimal types need to support at least digits 18.
67 -- For the rest, however, no requirements exist for the minimal small
68 -- and range that need to be supported.
73 -- 'Image and 'Wide_Image (see RM 3.5(34))
75 -- These attributes return a decimal real literal best approximating
76 -- the value (rounded away from zero if halfway between) with a
77 -- single leading character that is either a minus sign or a space,
78 -- one or more digits before the decimal point (with no redundant
79 -- leading zeros), a decimal point, and N digits after the decimal
80 -- point. For a subtype S, the value of N is S'Aft, the smallest
81 -- positive integer such that (10**N)*S'Delta is greater or equal to
82 -- one, see RM 3.5.10(5).
84 -- For an arbitrary small, this means large number arithmetic needs
87 -- Put (see RM A.10.9(22-26))
89 -- The requirements for Put add no extra constraints over the image
90 -- attributes, although it would be nice to be able to output more
91 -- than S'Aft digits after the decimal point for values of subtype S.
93 -- 'Value and 'Wide_Value attribute (RM 3.5(40-55))
95 -- Since the input can be given in any base in the range 2..16,
96 -- accurate conversion to a fixed point number may require
97 -- arbitrary precision arithmetic if there is no limit on the
98 -- magnitude of the small of the fixed point type.
100 -- Get (see RM A.10.9(12-21))
102 -- The requirements for Get are identical to those of the Value
105 -- ------------------------------
106 -- - Implementation Constraints -
107 -- ------------------------------
109 -- The requirements listed above for the input/output operations lead to
110 -- significant complexity, if no constraints are put on supported smalls.
112 -- Implementation Strategies
113 -- -------------------------
115 -- * Float arithmetic
116 -- * Arbitrary-precision integer arithmetic
117 -- * Fixed-precision integer arithmetic
119 -- Although it seems convenient to convert fixed point numbers to floating-
120 -- point and then print them, this leads to a number of restrictions.
121 -- The first one is precision. The widest floating-point type generally
122 -- available has 53 bits of mantissa. This means that Fine_Delta cannot
123 -- be less than 2.0**(-53).
125 -- In GNAT, Fine_Delta is 2.0**(-63), and Duration for example is a
126 -- 64-bit type. It would still be possible to use multi-precision
127 -- floating-point to perform calculations using longer mantissas,
128 -- but this is a much harder approach.
130 -- The base conversions needed for input and output of (non-decimal)
131 -- fixed point types can be seen as pairs of integer multiplications
134 -- Arbitrary-precision integer arithmetic would be suitable for the job
135 -- at hand, but has the draw-back that it is very heavy implementation-wise.
136 -- Especially in embedded systems, where fixed point types are often used,
137 -- it may not be desirable to require large amounts of storage and time
138 -- for fixed I/O operations.
140 -- Fixed-precision integer arithmetic has the advantage of simplicity and
141 -- speed. For the most common fixed point types this would be a perfect
142 -- solution. The downside however may be a too limited set of acceptable
143 -- fixed point types.
148 -- Using a scaled divide which truncates and returns a remainder R,
149 -- another E trailing digits can be calculated by computing the value
150 -- (R * (10.0**E)) / Z using another scaled divide. This procedure
151 -- can be repeated to compute an arbitrary number of digits in linear
152 -- time and storage. The last scaled divide should be rounded, with
153 -- a possible carry propagating to the more significant digits, to
154 -- ensure correct rounding of the unit in the last place.
156 -- An extension of this technique is to limit the value of Q to 9 decimal
157 -- digits, since 32-bit integers can be much more efficient than 64-bit
158 -- integers to output.
160 with Interfaces
; use Interfaces
;
161 with System
.Arith_64
; use System
.Arith_64
;
162 with System
.Img_Real
; use System
.Img_Real
;
163 with Ada
.Text_IO
; use Ada
.Text_IO
;
164 with Ada
.Text_IO
.Float_Aux
;
165 with Ada
.Text_IO
.Generic_Aux
;
167 package body Ada
.Text_IO
.Fixed_IO
is
169 -- Note: we still use the floating-point I/O routines for input of
170 -- ordinary fixed-point and output using exponent format. This will
171 -- result in inaccuracies for fixed point types with a small that is
172 -- not a power of two, and for types that require more precision than
173 -- is available in Long_Long_Float.
175 package Aux
renames Ada
.Text_IO
.Float_Aux
;
177 Extra_Layout_Space
: constant Field
:= 5 + Num
'Fore;
178 -- Extra space that may be needed for output of sign, decimal point,
179 -- exponent indication and mandatory decimals after and before the
180 -- decimal point. A string with length
182 -- Fore + Aft + Exp + Extra_Layout_Space
184 -- is always long enough for formatting any fixed point number
186 -- Implementation of Put routines
188 -- The following section describes a specific implementation choice for
189 -- performing base conversions needed for output of values of a fixed
190 -- point type T with small T'Small. The goal is to be able to output
191 -- all values of types with a precision of 64 bits and a delta of at
192 -- least 2.0**(-63), as these are current GNAT limitations already.
194 -- The chosen algorithm uses fixed precision integer arithmetic for
195 -- reasons of simplicity and efficiency. It is important to understand
196 -- in what ways the most simple and accurate approach to fixed point I/O
197 -- is limiting, before considering more complicated schemes.
199 -- Without loss of generality assume T has a range (-2.0**63) * T'Small
200 -- .. (2.0**63 - 1) * T'Small, and is output with Aft digits after the
201 -- decimal point and T'Fore - 1 before. If T'Small is integer, or
202 -- 1.0 / T'Small is integer, let S = T'Small and E = 0. For other T'Small,
203 -- let S and E be integers such that S / 10**E best approximates T'Small
204 -- and S is in the range 10**17 .. 10**18 - 1. The extra decimal scaling
205 -- factor 10**E can be trivially handled during final output, by adjusting
206 -- the decimal point or exponent.
208 -- Convert a value X * S of type T to a 64-bit integer value Q equal
209 -- to 10.0**D * (X * S) rounded to the nearest integer.
210 -- This conversion is a scaled integer divide of the form
214 -- where all variables are 64-bit signed integers using 2's complement,
215 -- and both the multiplication and division are done using full
216 -- intermediate precision. The final decimal value to be output is
220 -- This value can be written to the output file or to the result string
221 -- according to the format described in RM A.3.10. The details of this
222 -- operation are omitted here.
224 -- A 64-bit value can contain all integers with 18 decimal digits, but
225 -- not all with 19 decimal digits. If the total number of requested output
226 -- digits (Fore - 1) + Aft is greater than 18, for purposes of the
227 -- conversion Aft is adjusted to 18 - (Fore - 1). In that case, or
228 -- when Fore > 19, trailing zeros can complete the output after writing
229 -- the first 18 significant digits, or the technique described in the
230 -- next section can be used.
232 -- The final expression for D is
234 -- D := Integer'Max (-18, Integer'Min (Aft, 18 - (Fore - 1)));
236 -- For Y and Z the following expressions can be derived:
238 -- Q / (10.0**D) = X * S
240 -- Q = X * S * (10.0**D) = (X * Y) / Z
242 -- S * 10.0**D = Y / Z;
244 -- If S is an integer greater than or equal to one, then Fore must be at
245 -- least 20 in order to print T'First, which is at most -2.0**63.
246 -- This means D < 0, so use
248 -- (1) Y = -S and Z = -10**(-D)
250 -- If 1.0 / S is an integer greater than one, use
252 -- (2) Y = -10**D and Z = -(1.0 / S), for D >= 0
256 -- (3) Y = 1 and Z = (1.0 / S) * 10**(-D), for D < 0
258 -- Negative values are used for nominator Y and denominator Z, so that S
259 -- can have a maximum value of 2.0**63 and a minimum of 2.0**(-63).
260 -- For Z in -1 .. -9, Fore will still be 20, and D will be negative, as
261 -- (-2.0**63) / -9 is greater than 10**18. In these cases there is room
262 -- in the denominator for the extra decimal scaling required, so case (3)
263 -- will not overflow.
265 pragma Assert
(System
.Fine_Delta
>= 2.0**(-63));
266 pragma Assert
(Num
'Small in 2.0**(-63) .. 2.0**63);
267 pragma Assert
(Num
'Fore <= 37);
268 -- These assertions need to be relaxed to allow for a Small of
269 -- 2.0**(-64) at least, since there is an ACATS test for this ???
271 Max_Digits
: constant := 18;
272 -- Maximum number of decimal digits that can be represented in a
273 -- 64-bit signed number, see above
275 -- The constants E0 .. E5 implement a binary search for the appropriate
276 -- power of ten to scale the small so that it has one digit before the
279 subtype Int
is Integer;
280 E0
: constant Int
:= -(20 * Boolean'Pos (Num
'Small >= 1.0E1
));
281 E1
: constant Int
:= E0
+ 10 * Boolean'Pos (Num
'Small * 10.0**E0
< 1.0E-10);
282 E2
: constant Int
:= E1
+ 5 * Boolean'Pos (Num
'Small * 10.0**E1
< 1.0E-5);
283 E3
: constant Int
:= E2
+ 3 * Boolean'Pos (Num
'Small * 10.0**E2
< 1.0E-3);
284 E4
: constant Int
:= E3
+ 2 * Boolean'Pos (Num
'Small * 10.0**E3
< 1.0E-1);
285 E5
: constant Int
:= E4
+ 1 * Boolean'Pos (Num
'Small * 10.0**E4
< 1.0E-0);
287 Scale
: constant Integer := E5
;
289 pragma Assert
(Num
'Small * 10.0**Scale
>= 1.0
290 and then Num
'Small * 10.0**Scale
< 10.0);
292 Exact
: constant Boolean :=
293 Float'Floor (Num
'Small) = Float'Ceiling (Num
'Small)
294 or Float'Floor (1.0 / Num
'Small) = Float'Ceiling (1.0 / Num
'Small)
295 or Num
'Small >= 10.0**Max_Digits
;
296 -- True iff a numerator and denominator can be calculated such that
297 -- their ratio exactly represents the small of Num.
306 -- Actual output function, used internally by all other Put routines
317 pragma Unsuppress
(Range_Check
);
319 Aux
.Get
(File
, Long_Long_Float (Item
), Width
);
321 when Constraint_Error
=> raise Data_Error
;
328 pragma Unsuppress
(Range_Check
);
330 Aux
.Get
(Current_In
, Long_Long_Float (Item
), Width
);
332 when Constraint_Error
=> raise Data_Error
;
340 pragma Unsuppress
(Range_Check
);
342 Aux
.Gets
(From
, Long_Long_Float (Item
), Last
);
344 when Constraint_Error
=> raise Data_Error
;
354 Fore
: Field
:= Default_Fore
;
355 Aft
: Field
:= Default_Aft
;
356 Exp
: Field
:= Default_Exp
)
358 S
: String (1 .. Fore
+ Aft
+ Exp
+ Extra_Layout_Space
);
361 Put
(S
, Last
, Item
, Fore
, Aft
, Exp
);
362 Generic_Aux
.Put_Item
(File
, S
(1 .. Last
));
367 Fore
: Field
:= Default_Fore
;
368 Aft
: Field
:= Default_Aft
;
369 Exp
: Field
:= Default_Exp
)
371 S
: String (1 .. Fore
+ Aft
+ Exp
+ Extra_Layout_Space
);
374 Put
(S
, Last
, Item
, Fore
, Aft
, Exp
);
375 Generic_Aux
.Put_Item
(Text_IO
.Current_Out
, S
(1 .. Last
));
381 Aft
: Field
:= Default_Aft
;
382 Exp
: Field
:= Default_Exp
)
384 Fore
: constant Integer :=
387 - Field
'Max (1, Aft
) -- Decimal part
388 - Boolean'Pos (Exp
/= 0) -- Exponent indicator
394 if Fore
- Boolean'Pos (Item
< 0.0) < 1 or else Fore
> Field
'Last then
398 Put
(To
, Last
, Item
, Fore
, Aft
, Exp
);
400 if Last
/= To
'Last then
413 subtype Digit
is Int64
range 0 .. 9;
415 X
: constant Int64
:= Int64
'Integer_Value (Item
);
416 A
: constant Field
:= Field
'Max (Aft
, 1);
417 Neg
: constant Boolean := (Item
< 0.0);
418 Pos
: Integer := 0; -- Next digit X has value X * 10.0**Pos;
420 procedure Put_Character
(C
: Character);
421 pragma Inline
(Put_Character
);
422 -- Add C to the output string To, updating Last
424 procedure Put_Digit
(X
: Digit
);
425 -- Add digit X to the output string (going from left to right), updating
426 -- Last and Pos, and inserting the sign, leading zeros or a decimal
427 -- point when necessary. After outputting the first digit, Pos must not
428 -- be changed outside Put_Digit anymore.
430 procedure Put_Int64
(X
: Int64
; Scale
: Integer);
431 -- Output the decimal number abs X * 10**Scale
437 -- Output the decimal number (X * Y / Z) * 10**E, producing A digits
438 -- after the decimal point and rounding the final digit. The value
439 -- X * Y / Z is computed with full precision, but must be in the
446 procedure Put_Character
(C
: Character) is
450 -- Never put a character outside of string To. Exception Layout_Error
451 -- will be raised later if Last is greater than To'Last.
453 if Last
<= To
'Last then
462 procedure Put_Digit
(X
: Digit
) is
463 Digs
: constant array (Digit
) of Character := "0123456789";
466 if Last
= To
'First - 1 then
467 if X
/= 0 or Pos
<= 0 then
469 -- Before outputting first digit, include leading space,
470 -- possible minus sign and, if the first digit is fractional,
471 -- decimal seperator and leading zeros.
473 -- The Fore part has Pos + 1 + Boolean'Pos (Neg) characters,
474 -- if Pos >= 0 and otherwise has a single zero digit plus minus
475 -- sign if negative. Add leading space if necessary.
477 for J
in Integer'Max (0, Pos
) + 2 + Boolean'Pos (Neg
) .. Fore
482 -- Output minus sign, if number is negative
488 -- If starting with fractional digit, output leading zeros
494 for J
in Pos
.. -2 loop
499 Put_Character
(Digs
(X
));
503 -- This is not the first digit to be output, so the only
504 -- special handling is that for the decimal point
510 Put_Character
(Digs
(X
));
520 procedure Put_Int64
(X
: Int64
; Scale
: Integer) is
526 if X
not in -9 .. 9 then
527 Put_Int64
(X
/ 10, Scale
+ 1);
530 -- Use Put_Digit to advance Pos. This fixes a case where the second
531 -- or later Scaled_Divide would omit leading zeroes, resulting in
532 -- too few digits produced and a Layout_Error as result.
534 while Pos
> Scale
loop
538 -- If and only if more than one digit is output before the decimal
539 -- point, pos will be unequal to scale when outputting the first
542 pragma Assert
(Pos
= Scale
or else Last
= To
'First - 1);
546 Put_Digit
(abs (X
rem 10));
558 pragma Assert
(E
>= -Max_Digits
);
559 AA
: constant Field
:= E
+ A
;
560 N
: constant Natural := (AA
+ Max_Digits
- 1) / Max_Digits
+ 1;
562 Q
: array (0 .. N
- 1) of Int64
:= (others => 0);
563 -- Each element of Q has Max_Digits decimal digits, except the
564 -- last, which has eAA rem Max_Digits. Only Q (Q'First) may have an
565 -- absolute value equal to or larger than 10**Max_Digits. Only the
566 -- absolute value of the elements is not significant, not the sign.
572 for J
in Q
'Range loop
576 YY
:= 10**(Integer'Min (Max_Digits
, AA
- (J
- 1) * Max_Digits
));
579 Scaled_Divide
(XX
, YY
, Z
, Q
(J
), R
=> XX
, Round
=> False);
583 pragma Assert
(N
= 1);
585 Discard_Extra_Digits
: declare
586 Factor
: constant Int64
:= 10**(-E
- A
);
589 -- The scaling factors were such that the first division
590 -- produced more digits than requested. So divide away extra
591 -- digits and compute new remainder for later rounding.
593 if abs (Q
(0) rem Factor
) >= Factor
/ 2 then
594 Q
(0) := abs (Q
(0) / Factor
) + 1;
596 Q
(0) := Q
(0) / Factor
;
600 end Discard_Extra_Digits
;
603 -- At this point XX is a remainder and we need to determine if the
604 -- quotient in Q must be rounded away from zero.
606 -- As XX is less than the divisor, it is safe to take its absolute
607 -- without chance of overflow. The check to see if XX is at least
608 -- half the absolute value of the divisor must be done carefully to
609 -- avoid overflow or lose precision.
614 or else (Z
< 0 and then (-XX
) * 2 <= Z
)
615 or else (Z
>= 0 and then XX
* 2 >= Z
)
617 -- OK, rounding is necessary. As the sign is not significant,
618 -- take advantage of the fact that an extra negative value will
619 -- always be available when propagating the carry.
621 Q
(Q
'Last) := -abs Q
(Q
'Last) - 1;
624 for J
in reverse 1 .. Q
'Last loop
625 if Q
(J
) = YY
or else Q
(J
) = -YY
then
627 Q
(J
- 1) := -abs Q
(J
- 1) - 1;
630 exit Propagate_Carry
;
632 end loop Propagate_Carry
;
635 for J
in Q
'First .. Q
'Last - 1 loop
636 Put_Int64
(Q
(J
), E
- J
* Max_Digits
);
639 Put_Int64
(Q
(Q
'Last), -A
);
642 -- Start of processing for Put
645 Last
:= To
'First - 1;
649 -- With the Exp format, it is not known how many output digits to
650 -- generate, as leading zeros must be ignored. Computing too many
651 -- digits and then truncating the output will not give the closest
652 -- output, it is necessary to round at the correct digit.
654 -- The general approach is as follows: as long as no digits have
655 -- been generated, compute the Aft next digits (without rounding).
656 -- Once a non-zero digit is generated, determine the exact number
657 -- of digits remaining and compute them with rounding.
659 -- Since a large number of iterations might be necessary in case
660 -- of Aft = 1, the following optimization would be desirable.
662 -- Count the number Z of leading zero bits in the integer
663 -- representation of X, and start with producing Aft + Z * 1000 /
664 -- 3322 digits in the first scaled division.
666 -- However, the floating-point routines are still used now ???
668 System
.Img_Real
.Set_Image_Real
(Long_Long_Float (Item
), To
, Last
,
675 D
: constant Integer := Integer'Min (A
, Max_Digits
677 Y
: constant Int64
:= Int64
'Min (Int64
(-Num
'Small), -1)
678 * 10**Integer'Max (0, D
);
679 Z
: constant Int64
:= Int64
'Min (Int64
(-(1.0 / Num
'Small)), -1)
680 * 10**Integer'Max (0, -D
);
682 Put_Scaled
(X
, Y
, Z
, A
, -D
);
687 E
: constant Integer := Max_Digits
- 1 + Scale
;
688 D
: constant Integer := Scale
- 1;
689 Y
: constant Int64
:= Int64
(-Num
'Small * 10.0**E
);
690 Z
: constant Int64
:= -10**Max_Digits
;
692 Put_Scaled
(X
, Y
, Z
, A
, -D
);
696 -- If only zero digits encountered, unit digit has not been output yet
698 if Last
< To
'First then
701 elsif Last
> To
'Last then
702 raise Layout_Error
; -- Not enough room in the output variable
705 -- Always output digits up to the first one after the decimal point
712 end Ada
.Text_IO
.Fixed_IO
;