Follow @Openwall on Twitter for new release announcements and other news
[<prev] [next>] [<thread-prev] [thread-next>] [day] [month] [year] [list]
Date: Mon, 25 Feb 2019 16:51:09 +0100
From: Markus Wichmann <>
Subject: Re: FE Exception triggered by comparison

On Mon, Feb 25, 2019 at 08:50:52AM +1100, Damian McGuckin wrote:
> The context of this is that I want a coding style which means I can compare
> numbers without affecting the exception state. And it must have zero
> overhead, and not affect the readability of the code, i.e. no function
> calls.

Yet another problem brought to you by premature optimization. What you
want to know is if a certain number is NaN. There's a perfectly
acceptable idiom for that:

if (isnan(x)) {

This (the exception stuff) is the reason why the special cases are
always front-loaded in musl. So they can be sorted out without raising
spurious exceptions.

The only reason the above may not be acceptable to you is that it looks
like a function call. But it isn't. isnan() is a macro that doesn't
always revert to a function call.

> I want to know that
> 	x != x
> will always detect any NaN with affecting the exception status and that
> comparisons like
> 	if (x == x) { ... }
> 	else if (x > y) { .... }
> 	else if (x < y) { .... }
> 	else { x or y are NaN }
> will similarly also not modify the exception status, and in the last section
> let me process how I interpret the NaNs.

Well, sorry, but these instructions do not work that way. Any operation
on a NaN, including comparison, even comparison for equality, will raise
IE, at least if it is an sNaN.

Honestly, though, I wonder what the big deal is. In most cases, if you
see a NaN, someone probably just made an invalid operation, or chose to
start another invalid operation with your function. In which case
raising IE is not spurious at all.

> Otherwise, avoidance of creating spurious exceptions forces you to start
> working at the IEEE 754 encoding level.

Or you could just use the interface provided by the C standard:

if (!isnormal(x) || !isnormal(y)) {
    guard clause here;
/* definitely normal x and y from this point on. */

Hopefully you don't need to deal with subnormals...

> This is counterproductive to clear
> and concise programming. Such a style is riddled through a lot of the maths
> routines in MUSL and the libraries that came before it.

No, that's just an optimization. Musl strives to minimize the numeric
error while also delivering good performance, and that means that often
a lot of boundary conditions can be detected at the same time with a
single comparison (e.g. you can detect "x < 0 || x > 2**limit ||
isinf(x)" by detecting if the exponent and sign bit together exceed a
certain limit.)

But nothing is stopping you from writing these conditions out entirely.


Powered by blists - more mailing lists

Confused about mailing lists and their use? Read about mailing lists on Wikipedia and check out these guidelines on proper formatting of your messages.