Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between 2.0 and 2.0f (explicit float vs double literals)

Tags:

c++

c

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

like image 997
Justin Meiners Avatar asked Sep 12 '10 22:09

Justin Meiners


People also ask

What is the difference between 2.0 and 2.0 F?

2.0 is a double literal value. 2.0f is a float literal value.

What is the difference between a double and a float 2 differences?

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.

What is the difference between float and double float?

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.

What is better float or double?

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.


2 Answers

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
like image 161
Johannes Schaub - litb Avatar answered Sep 22 '22 12:09

Johannes Schaub - litb


I's rarely about speed (at least directly), but the fact that otherwise the compiler will warn about converting double to float.

like image 30
Jerry Coffin Avatar answered Sep 22 '22 12:09

Jerry Coffin