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
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:
#include <cmath>
#include <iostream>
int main()
{
std::cout << std::pow(-1.0f, 20000001) << "\n";
std::cout << std::pow(-1.0f, (float) 20000001) << "\n";
}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.
0
Jul 07 '24
[deleted]
2
u/fdwr fdwr@github 🔍 Jul 08 '24
I guess it stands for ASCII,
Hmm, apparently so: https://minnie.tuhs.org/cgi-bin/utree.pl?file=V1/man/man3/atoi.3 I always thought it stood for alphanumeric-to-integer (and not ASCII-specific, since it worked on EBCDIC machines too).
1
u/HugoNikanor Jul 09 '24
But then there's also the strtol family which doesn't take a string but takes a char *. Presumably the str in strtol stands for 'not a string'?
strtollis borrowed from C, wherechar *for strings is the norm.
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 calling pow(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.
5
u/IyeOnline Jul 07 '24
That is because the
cmathheader only puts the C standard library functions into the global namespace, meaning that the C library function fordoubles is the only possible overload. The C++-adaptedmath.hmay put all functions form the C++ standard library into the global namespace, so thefloatoverload is available.
1
u/markuspeloquin Jul 07 '24
Weird. I've been writing Go a lot lately, and a literal 2 would 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:
C++ has a bunch of baggage from the 1970s and C compatibility.
you should check the signature and documentation of library functions.
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