[LAD] Is -ffast-math safe for audio?

Fons Adriaensen fons at linuxaudio.org
Sat Nov 24 11:14:06 CET 2018


On Thu, Nov 22, 2018 at 11:29:11PM +0100, Robin Gareus wrote:

> A simpler example to show this is
> 
> #include <stdio.h>
> #include <math.h>
> int main (int argc, char** argv) {
>   float a = 0;
>   for (int i = 0; i < 100; ++i) {
>     a += 0.1f;
>     a -= 0.05f;
>     a = fmodf (a, 1.f);
>   }
>   printf ("%f\n", a);
>   return 0;
> }
> 
> using gcc 6.3.0-18+deb9u1, x86_64, this
> prints 1.000000 (when compiled with -O0)
> and    0.000001 (when compiled with -O2 --fast-math)

Actually 0.999999940 and 0.000000596.

The 1.000000 would imply that the fmodf (a, 1.0f) would be
plain wrong, but it isn't.

The examples shown in this thread all involve converting
floats to ints. Typical application of this in audio is
to convert a float index into a wavetable to an int index
and a float < 1 interpolation argument.

The dangerous thing to do is: 

// given float p

int i = (int) floorf (p);
float f = fmodf (p, 1.0f);

as you could end up with i + f != p.

The safe way is of course:

int i = (int) floorf (p);
float f = p - i;


Ciao,

-- 
FA



More information about the Linux-audio-dev mailing list