Implementing C99's roundf(), round(), and roundl()
Steve Kargl
sgk at troutmask.apl.washington.edu
Mon Dec 1 12:35:48 PST 2003
On Mon, Dec 01, 2003 at 07:05:18PM +1100, Bruce Evans wrote:
> On Sun, 30 Nov 2003, David Schultz wrote:
>
> > On Sat, Nov 29, 2003, Steve Kargl wrote:
> > > On Sat, Nov 29, 2003 at 12:09:11AM -0800, David Schultz wrote:
> > > > On Fri, Nov 28, 2003, Steve Kargl wrote:
> > > > > Can the math functions round[fl]() be implemented in
> > > > > terms of other math(3) functions and still conform to the
> > > > > C99 and POSIX standard? For example,
> > > > > [code moved later]
> > > >
> > > > This looks correct to me at first glance, modulo possible problems
> > > > with overflow. ...
> > >
> > > I don't undrestand your overflow comment. ceil[f]() can return Inf
> > > and nan, but in those cases round[f]() should also return Inf and nan.
> > > The two operations, (t-x) and (t+x), should yield a value in the
> > > range [0,1). I'll submit a PR with a man page.
> >
> > The concern was that ceil() could round a number up to infinity
> > when round() is supposed to round the number down. But now that I
> > think about it at a reasonable hour, this concern is clearly
> > bogus. In base two floating point representations, there isn't
> > enough precision to get numbers that large with nonzero fractional
> > parts.
>
> It's not completely obvious. I thought of it soon but wondered if I
> thought of all the cases. Steve's remark about Infs and NaNs points
> to possible problems:
>
> > > > > #include <math.h>
> > > > >
> > > > > float roundf(float x) {
> > > > > float t;
> > > > > if (x >= 0.0) {
>
> Suppose x is a NaN. Then it will compare strangely with everything and
> we won't get here.
I must admit I never thought about the case where round() is called with
a NaN as its argument. I just checked the on-line POSIX SUSv3 documents and
found:
Upon successful completion, these functions shall return the rounded
integer value.
[MX] If x is NaN, a NaN shall be returned.
If x is +-0 or +-Inf, x shall be returned.
[XSI] If the correct value would cause overflow, a range error shall
occur and round(), roundf(), and roundl() shall return the value of
the macro +-HUGE_VAL, +-HUGE_VALF, and +-HUGE_VALL (with the same sign
as x), respectively.
I, of course, did not check for these special values.
> All the other corner cases need to be checked. It's possibly to check
> all 2^32 cases for floats (once you know the correct results).
Do you have code to do this check?
> Other things to check: setting of exception flags. I'm not sure if the
> settings by ceil() are the right ones and the only ones.
AFAICT, we can't do the exception handling according to POSIX, because
we don't have <fenv.h>, feclearexcept(), and fetestexcept() implemented,
yet.
--
Steve
More information about the freebsd-standards
mailing list