delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1997/06/13/23:49:51

From: cziwkga AT ulcc DOT ac DOT uk (Kevin Ashley)
Newsgroups: comp.os.msdos.djgpp
Subject: Re: how to convert float ->int?
Date: 11 Jun 1997 12:47:58 GMT
Organization: University of London Computer Centre
Lines: 34
Distribution: world
Message-ID: <5nm6pu$a5f@calypso.ulcc.ac.uk>
References: <Pine DOT D-G DOT 3 DOT 91 DOT 970606141323 DOT 12912N-100000 AT dg1>
Reply-To: k DOT ashley AT ulcc DOT ac DOT uk
NNTP-Posting-Host: silver.ulcc.ac.uk
To: djgpp AT delorie DOT com
DJ-Gateway: from newsgroup comp.os.msdos.djgpp

In article <Pine DOT D-G DOT 3 DOT 91 DOT 970606141323 DOT 12912N-100000 AT dg1>, "Art S. Kagel" <kagel AT ns1 DOT bloomberg DOT com> writes:
|>On 4 Jun 1997, Real Email in Sig! wrote:
..
|>> 
|>> How about a=(b+0.5); for a rounded answer?  Seems right, but I've been
|>> wrong on easier stuff before.
|>
|>  a=(b+0.5005)  is better to handle rounding of values not exactly 
|>representable in IEEE float formats.

No - this produces an consistent bias to round towards positive infinity
which is worse than the error induced by imprecise representation.
My own feeling is that if a number is so close to x.5 that it cannot
be precisely represented then one should expect that it might be
rounded up or down depending on the exact value of x. Your solution means
it is much more likely to be rounded up.

But also, everyone in this thread has forgotten negative numbers.
Saying that a=b+0.5 is an acceptable way to round the float b to the
int a is only true if b is positive. If b is negative, this will result
in incorrect rounding: e.g. -1.2 will be rounded to 0 and -1.7 to -1
instead of -2. What you need is

a = b+(0.5*SIGN(b))

where SIGN(x) is 1 if x >= 0 and -1 otherwise. Alternatively,
one of us needs to volunteer to add rint() to DJGPP's libm implementation.

-----------------------------------------------------------------------------
Kevin Ashley                              K DOT Ashley AT Ulcc DOT ac DOT uk
Development Manager                http://www.ulcc.ac.uk/staff/Kevin+Ashley
University of London Computer Centre.      ...ukc!ncdlab!K.Ashley
                      This is not a signature

- Raw text -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019