2.0 和 2.0f 之间的差异(显式浮点型与双精度型文字)
我对将 f
放在文字值旁边有一些疑问。我知道它将它定义为 float
但我真的需要它吗? 这个 2.0f * 2.0f
是否比 2.0 * 2.0
更快或编译有什么不同?像 float a = 2.0;
这样的语句与 float a = 2.0f;
的编译方式是否不同?
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;
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
有时您需要它显式具有
float
类型,如以下情况所示Sometimes you need it to explicitly have type
float
, like in the following case我很少关注速度(至少不直接关注),但事实是,否则编译器会警告将
double
转换为float
。I's rarely about speed (at least directly), but the fact that otherwise the compiler will warn about converting
double
tofloat
.AFAIK,在“普通”PC(x86 和 x87-就像数学协处理器一样)速度的差异是无关紧要的,因为计算无论如何都是在内部以 80 位精度完成的。
当您有大量浮点数需要管理(科学计算或类似的东西)时,浮点数可能会变得很重要,因此使用较小的数据类型可能会很方便,既可以使用更少的内存,也可以更快地从 RAM/ 中读取它们磁盘。
在缺少浮点单元的机器(例如大多数微控制器)上使用浮点代替双精度也可能很有用,其中所有浮点算术都是通过编译器插入的代码在软件中执行的;在这种情况下,浮点运算的速度可能会有所提高(在这种环境中,每一位内存通常都很重要)。
在 PC 上,IMO 您可以在“正常”上下文中使用 double,只需尽量避免在同一表达式中混合数据类型(双精度、浮点型、整数……),以避免不必要的昂贵转换。无论如何,对于文字,编译器应该足够聪明,可以在编译时执行转换。
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.