this post was submitted on 10 Apr 2025
11 points (100.0% liked)
C++
1960 readers
1 users here now
The center for all discussion and news regarding C++.
Rules
- Respect instance rules.
- Don't be a jerk.
- Please keep all posts related to C++.
founded 2 years ago
MODERATORS
you are viewing a single comment's thread
view the rest of the comments
view the rest of the comments
Use
-ffast-math
... if you dare. Or just useThe reason it doesn't optimise it into one multiplication is because that isn't actually the same calculation. Floating point numbers aren't real numbers, so it isn't true that
(a * b) / c == (a / c) * b
. Since the "optimisation" would actually change the semantics, compilers don't do it by default.-ffast-math
says "hey I don't care about reliable semantics; just do whatever to make it fast". But it also does a load of stuff that you may find surprising. so you really shouldn't use it. Much better just to reorganise your code.You can also use
-funsafe-math-optimizations
which is the more specific subset of-ffast-math
that does this particular optimisation. See https://gcc.gnu.org/wiki/FloatingPointMathAlso I would question if it matters. This micro-optimisation will make zero difference on x86. On a microcontroller (I assume what you're actually using if you're encoding motor positions) it might matter a bit more but double check your microcontroller even has an FPU. Lots don't. Even if it does, doing it in integer space will probably be faster (though not necessarily).
Very interesting comment. Thanks.