Justin Meiners
Justin Meiners

Reputation: 11113

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

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

Upvotes: 11

Views: 23934

Answers (3)

Matteo Italia
Matteo Italia

Reputation: 126787

AFAIK, on "normal" PCs (x86 with x87-like mathematical coprocessor) the difference in speed is irrelevant, since the calculations are internally done anyway in 80-bit precision.

Floats may gain importance when you have large arrays of floating-point numbers to manage (scientific calculations or stuff like that), so having a smaller data type may be convenient, both to use less memory and to be faster to read them from RAM/disk.

It may also be useful to use floats instead of doubles on machines that lack a floating point unit (e.g. most microcontrollers), where all the floating-point arithmetic is performed in software by code inserted by the compiler; in this case, there may be a gain in speed operating on floats (and in such environments often also every bit of memory matters).

On PCs, IMO you can just use double in "normal" contexts, just try to avoid mixing datatypes (double, floats, ints, ...) in the same expression to avoid unnecessary costly conversions. Anyhow, with literals the compiler should be smart enough to perform the conversion at compile time.

Upvotes: 3

Johannes Schaub - litb
Johannes Schaub - litb

Reputation: 506935

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

Upvotes: 21

Jerry Coffin
Jerry Coffin

Reputation: 490108

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

Upvotes: 6

Related Questions