Precalculation of float operations in code

Asked by benjamin

Hello,

I noticed that the following code :

int v1,v2;
v1 = v2*3*4;

will produce the same output as

int v1,v2;
v1 = v2*12;

but with floats, two separate calls to __aeabi_fmul are made in the first case against only one in the second one.

On the otherside, when putting the operations in defines, the preprocessor precompute the (3.f*4.f) part and so only one call to __aeabi_fmul is issued.

Is it possible to precompute float operations in code in the same way it is done with integers or by the preprocessor?

Question information

Language:
English Edit question
Status:
Solved
For:
GNU Arm Embedded Toolchain Edit question
Assignee:
No assignee Edit question
Solved by:
benjamin
Solved:
Last query:
Last reply:
Revision history for this message
Thomas Preud'homme (thomas-preudhomme) said :
#1

Hi Benjamin,

the reason for the difference is that v2 * 3.f * 4.f which is equivalent to (v2 * 3.f) * 4.f might not give the same result as v1 * (3.f * 4.f) due to rounding error. If you really want this you can use -ffast-math. Note that ffast-math will also enable other unsafe optimizations for float. Alternatively you might want to use -fassociative-math -fno-signed-zeros -fno-trapping-math. fassociative-math is what allows this optimization and as the manual states it can only be enabled if the two other switch are also enabled.

Before doing so I urge you to take a look at the GCC manual to make sure you understand all the consequences of these optimizations.

Best regards.

Revision history for this message
benjamin (blackswords) said :
#2

Thanks for you answer

I will use parenthesis to group float constants operation from now. It's safer than relying on some optimizations