I had some questions about putting f
next to literal values. I know it defines it as a float
but do I really need it?
Is this 2.0f * 2.0f
any faster or compiled any different than 2.0 * 2.0
? Is a statement like float a = 2.0;
compiled differently than float a = 2.0f;
?
2.0 is a double literal value. 2.0f is a float literal value.
float is a 32-bit IEEE 754 single precision Floating Point Number – 1 bit for the sign, 8 bits for the exponent, and 23* for the value. float has 7 decimal digits of precision. double is a 64-bit IEEE 754 double precision Floating Point Number – 1 bit for the sign, 11 bits for the exponent, and 52* bits for the value.
float and double both have varying capacities when it comes to the number of decimal digits they can hold. float can hold up to 7 decimal digits accurately while double can hold up to 15.
double has higher precision, whereas floats take up less memory and are faster. In general you should use float unless you have a case where it isn't accurate enough. On typical modern computers, double is just as fast as float.
Sometimes you need it to explicitly have type float
, like in the following case
float f = ...;
float r = std::max(f, 42.0); // won't work; (float, double).
float r = std::max(f, 42.0f); // works: both have same type
I's rarely about speed (at least directly), but the fact that otherwise the compiler will warn about converting double
to float
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With