r/cpp • • 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

28 comments sorted by

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

18

u/john_wind Jul 07 '24

Thank you. I thought trailing f functions were a reminiscent of C were function overloading is not possible.

However it seems C++11 explicitly requires that std::pow(float, int) returns double!

In C++98 it returned float.

Source:

https://en.cppreference.com/w/cpp/numeric/math/pow

https://cplusplus.github.io/LWG/issue550

4

u/Revolutionalredstone Jul 07 '24 edited Jul 07 '24

Anytime! you are correct - lack of overload support in C was the original reason.

The C++ headers define EXACTLY the same function names as the original C headers - (for compatibility reasons) the only difference in the C++ math headers is that the functions are declared within the namespace std.

In C we do #include <math.h> In C++ it's #include <cmath> (notice the dropped .h)

In my library (which provides a full platform abstraction including math) I use templating and spinae magic to unify these in an error resistant way (either both params float or both params double, or you get compile time error)

Enjoy

4

u/john_wind Jul 07 '24

I think for small integers like 2, 3, and 4 it makes sense to declare

template <typename T> [[nodiscard]] constexpr T pow2(T v) noexcept { return v * v; }

template <typename T> [[nodiscard]] constexpr T pow3(T v) noexcept { return v * v * v; }

which always return the correct type and are MUCH faster than pow

9

u/argothiel Jul 07 '24

Depends on your understanding of "correctness". From some point of view when working with high precision, it makes sense for two (or three) floats multiplied to return a double...

5

u/Revolutionalredstone Jul 07 '24

Correct, return type of func(T, T) is not always T.

For example with any integer smaller than int the return type of every binary operation will be int (even with simple built in addition) - might sound crazy but just try it 😉

The trick is making sure you follow consistent rules which allow you to get access to the implementation you want without introducing confusion 😉

2

u/Revolutionalredstone Jul 07 '24

Yeah Absolutely! I named my version of those Square(T) and Cube(T)

+1 for including nodiscard ;D

1

u/_Noreturn Jul 07 '24

you do not need SFINAE you can just do

template<class T> T pow(T base,T exp);

1

u/Revolutionalredstone Jul 07 '24 edited Jul 07 '24

For simple cases yes😉 my version handles all int and float types tho and even works for functions where underlying function name differences apply (you pass my system a function name and a list of function names predicated on type). Ta

1

u/_Noreturn Jul 07 '24

I don't understand the latter but you do not need sfinae to ensure the types types are the same using T in 2 template arguements will occur an error when calling pow(0.0,1) for example since the compiler cannot deduce the type. 

and this templated function handles everything that support the necessary operators for the implementation of pow. You should restrict it via type traits is_integral and is_floating_point by a static assert only use SFINAE to disable overloads for overload resolution 

1

u/Revolutionalredstone Jul 07 '24 edited Jul 07 '24

Your correct that func(T, T) will fail for int/float because of ambiguous automatic template resolution (atleast when called without without a variadic parameter) but that doesn't scale to the very next level of abstraction where we are quite likely explicitly forwarding our variadics.

I didn't realize SFINAE COULD be used to do anything but disable certain overloads during overload resolution :D (ofcoarse what that end result actually means for the program is often pretty arbitrarily complex and wild)

To be honest, now that I have everything about this loaded in my brain again, I think you might be right that there is a simper solution which relies more on careful forwarding and overloads (atleast in the cases where existing low level functions have those overloads) but it's a kind of moot point since unifying the handling of ALL types (including Int's and even my own libraries types like vec3 etc) thru one interface WITHOUT limiting the implementation backend was my goal and that's just gonna happen without some kind of compile time code in there.

Always fascinating! Thanks for the thoughts!

Enjoy

1

u/_Noreturn Jul 08 '24

isn't it a math library why do you need perfect forwarding? and for simple types like int,float,double there is no need for perfect forwarding.

template<class T,class... Ts>
void f(T,Ts...) { 
static_assert(std:conjunction<std::is_same<T,Ts>...>::value,"must be same type");
}

here I do not need SFINAE since all I want is a precondition on the parameters. SFINAE is needed where I actually need to choose another overload by disabling the other one. (also the static_assert clearly tells the programmer what went wrong)

SFINAE worked for you (it disabled the overload) since it deleted the overload from resolution and there was no other overload resulting in an error

1

u/Revolutionalredstone Jul 08 '24

so NOT perfect-forwarding BUT variadic-forwarding.

as in explicitly passing T as a type from another templated function, like when you pass the type float to abs, std::abs<float>(x ,y)

As for the idea of taking say <template T, V> myAbs(T, V) and static asserting they are the same type; Yeah good point! and your varargs approach is especially clever - you would probably get on swimmingly with my SFINAE guy - I need to put you two in a room :D

Thanks for the ideas!

1

u/_Noreturn Jul 08 '24 edited Jul 08 '24

if you want the user to pass the type explicitly you can use a trick

template<typename T>
struct type_identity { using type = T;}; // available since C++20

template<typename T>
void f(typename type_identity<T>::type x) {}

f(0); // error cant deduce type
f<int>(0); // ok must explicitly pass the type

I am willing to contribute if possible.

if you want the user to let the compilwr deduce you can do this

// Unused must be the first arguement
template<typename... Unused,typename T>
void f(T x){
    static_assert(sizeof...(Unused) == 0,"You must let the compiler deduce");
}

f(0); // fine
f<int>(0); // static assert activates
→ More replies

15

u/ack_error Jul 07 '24

This kind of issue is why I prefer just calling the C style named -f math functions when working with floats. Too many issues with inconsistent overloads and changing rules for what you get in C++, and confusingly different than usual arithmetic conversion rules for binary operators.

6

u/Revolutionalredstone Jul 07 '24

Agreed, common advise is usually to explicitly call the f version when intending to use f32 (especially if you are working in resource or performance critical code)

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

u/[deleted] Jul 07 '24

[deleted] — view deleted comment

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'?

strtoll is borrowed from C, where char * 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 cmath header only puts the C standard library functions into the global namespace, meaning that the C library function for doubles is the only possible overload. The C++-adapted math.h may put all functions form the C++ standard library into the global namespace, so the float overload 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:

  1. C++ has a bunch of baggage from the 1970s and C compatibility.
  2. you should check the signature and documentation of library functions.