In C++ (or maybe only our compilers VC8 and VC10) 3.14
is a double literal and 3.14f
is a float literal.
Now I have a colleague that stated:
We should use float-literals for float calculations and double-literals for double calculations as this could have an impact on the precision of a calculation when constants are used in a calcualtion.
Specifically, I think he meant:
double d1, d2;
float f1, f2;
... init and stuff ...
f1 = 3.1415 * f2;
f1 = 3.1415f * f2; // any difference?
d1 = 3.1415 * d2;
d1 = 3.1415f * d2; // any difference?
Or, added by me, even:
d1 = 42 * d2;
d1 = 42.0f * d2; // any difference?
d1 = 42.0 * d2; // any difference?
More generally, the only point I can see for using 2.71828183f
is to make sure that the constant I'm trying to specify will actually fit into a float (compiler error/warning otherwise).
Can someone shed some light on this? Do you specify the f
postfix? Why?
To quote from an answer what I implicitly took for granted:
If you're working with a float variable and a double literal the whole
operation will be done as double and then converted back to float.
Could there possibly be any harm in this? (Other than a very, very theoretical performance impact?)
Further edit: It would be nice if answers containing technical details (appreciated!) could also include how these differences affect general purpose code. (Yes, if you're number crunching, you probably like to make sure your big-n floating point ops are as efficient (and correct) as possible -- but does it matter for general purpose code that's called a few times? Isn't it cleaner if the code just uses 0.0
and skips the -- hard to maintain! -- float suffix?)
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…