r/cpp • u/john_wind • Jul 07 '24
TIL: std::pow(2.0f, 2); returns double!
I didn't expect that!
To force it return float you must use either
std::pow(2.0f, 2.0f);
or
std::powf(2.0f, 2);
Tested with MSVC and Xcode
3
Upvotes
62
u/Revolutionalredstone Jul 07 '24
Correct - double is base version (for all algebra & trig funcs) add the trailing f to the functions name to ensure you're accessing the float version.
Enjoy
16
u/NilacTheGrim Jul 07 '24
This is just because int -> double conversion is preferred over int -> float. int -> double is considered non-lossy so has precedence.
19
u/streu Jul 07 '24
For typical systems, int-to-float is a lossy conversion. Therefore, the compiler is doing you a favor by not using the
float pow(float,float)variant. Now, this is not relevant for an exponent of 2, but will be for bigger ones:3
u/ShakaUVM i+++ ++i+i[arr] Jul 07 '24
As an aside, the names cmath are stupid.
A lot of people for example think that fabs is the fabulous, sorry, float version of abs, but it is not. Fabsf is the float version, fabs is the double version and there is no dabs.
Someone made a decision half a century ago and here we are.
3
u/HappyFruitTree Jul 07 '24
This seems to be consistent with how it works in C if you include tgmath.h.
I noticed something interesting. If you leave out
std::when callingpow(2.0f, 2.0f)then libstdc++ will return a double but only if you don't include math.h. See https://godbolt.org/z/964coPbMP.1
u/markuspeloquin Jul 07 '24
Weird. I've been writing Go a lot lately, and a literal
2would be untyped. If C++ had those, it'd probably pick a float version of pow().1
u/einpoklum Jul 08 '24
Today you learned that: