When we discovered the 'feature' in Ada that an implementor can pick how
he rounds, we discussed various ways to get the integer part of a number.
Here is the 'best' (meaning most portable) way: (p.s. this 'algorithm'
is obviously language-independent)
declare
x : real;
i : integer; -- integer part of x
begin
i := integer(x);
if (i > x) then
-- machine rounded up
i := i - 1;
end if;
end;
Dave Emery
until 7 Nov: ...princeton!siemens!emery
princeton!siemens!em...@seismo.css.gov
after 10 Nov: linus!emery
em...@mitre-bedford.arpa
x : float;
i : integer;
then the line
if (i > x) then ...
won't work, since ">" isn't defined between integers
and floats. This is perhaps what is meant:
if float(i) > x then ...
However, this does not really help the hard-core numerical
programmer, who most likely wants X rounded but left in
FLOATING representation - since otherwise he can use only
a very restricted subrange of float.
What we really need is the set
function FLOOR (X : FLOAT) return FLOAT;
CEIL
ROUND
TRUNC
and let's make them generic in the domain type.
The above algorithm only works for POSITIVE values of X! For example, if
X = -0.7 this will return -1 instead of 0. The "integer part of a real number"
is a truncate function:
function Trunc (X : Float) return Integer is
I : Integer := Integer (X);
begin
if I > 0 and then
Float(I) > X then
I := I - 1;
elsif I < 0 and then
Float(I) < X then
I := I + 1;
end if;
return I;
end Trunc;
This should return whatever is before the decimal point in a floating point
number.
Arny B. Engelson
{ihnp4 | bonnie | clyde } wayback!arny
(201) 386-4816
oops, made a type mismatch mistake in the last note:
comparison should be:
if (real(i) > x) then
i := i - 1; -- machine rounded up
There is no operation ">" (L : integer, R : real)....
Sorry about that, chief...
Dave Emery
Mitre Corp.
em...@mitre-bedford.arpa