From mboxrd@z Thu Jan 1 00:00:00 1970 X-Spam-Checker-Version: SpamAssassin 3.4.5-pre1 (2020-06-20) on ip-172-31-74-118.ec2.internal X-Spam-Level: X-Spam-Status: No, score=-1.9 required=3.0 tests=BAYES_00 autolearn=ham autolearn_force=no version=3.4.5-pre1 Date: 15 Nov 91 18:59:59 GMT From: milton!mfeldman@beaver.cs.washington.edu (Michael Feldman) Subject: Red-faced professor gets bitten in search for portability Message-ID: <1991Nov15.185959.5002@milton.u.washington.edu> List-Id: Asked by students whether Ada has an equivalent of the Pascal "Trunc" operation, which just returns the integer part of its argument, I put together a function based on the old trick we used in the Fortran days. FUNCTION Trunc (X: Float) RETURN Integer IS BEGIN RETURN Integer(X - 0.5); END Trunc; Since conversion of Float to Integer is, in Ada, a rounding operation, this looks like a good solution, right? WRONG! The trouble is that, according to the LRM, the result of the conversion is implementation- dependent if the fractional part of the float quantity lies just between the two integers (that is, = 0.5). (LRM sect. 4.6) To see the hidden nastiness here, suppose Y has an integral value. If Y = 10.0 (say), then Trunc(Y) returns 10 on compilers where the 0.5 case rounds _up_, and returns 9 on compilers where the 0.5 case rounds _down_. Oops! A simple bit of code falls right into a portability trap. The only solution seems to lie in forcing an integer division, since integer division indeed truncates, portably. So our new function is FUNCTION Trunc (X: Float) RETURN Integer IS BEGIN RETURN Integer(2.0 * X) / 2; END Trunc; which, I suppose, can be optimized efficiently, but seems like a kludgy way to do a simple truncation. I think this is an example of an operation that's much more easily done as an intrinsic than as a programmer-defined function. Any thoughts in net-land? By the way - I am all the more red-faced because I let the dangerous Trunc monster loose into a textbook. 'Course, I haven't run into another Ada text that even discusses the question... Always in search of the portable Ada program, I remain Mike ------------------------------------------------------------------------------- Michael B. Feldman Visiting Professor 1991-92 Professor Dept. of Comp. Sci. and Engrg. Dept. of Elect. Engrg. and Comp. Sci. University of Washington FR-35 The George Washington University Seattle, WA 98105 Washington, DC 20052 mfeldman@cs.washington.edu mfeldman@seas.gwu.edu (206) 632-3794 (voice) (202) 994-5253 (voice) (206) 543-2969 (fax) (202) 994-5296 (fax) -------------------------------------------------------------------------------