简体   繁体   English

为什么选择Float而不是Double?

[英]Why choose Float over Double or vice versa?

I'm a uni student and have started studying programming in java and as far as I can tell both float and double do the same thing, they are both for writing integers decimal places. 我是一名单身学生,已经开始研究Java编程,据我所知,float和double都做同样的事情,它们都用于写整数小数位。 However I feel I'm completely wrong as there obviously wouldn't be 2 commands to achieve the same thing. 但是我觉得我完全错了,因为显然不会有2条命令来实现相同的目的。 Can someone please explain if there is a difference and if possible expand on it by saying why a float wouldn't work in a double situation and vice versa. 有人可以解释一下是否存在差异,如果可能的话,请扩大其含义,并说出为什么在双重情况下浮动不起作用,反之亦然。

PS I'm not asking for answers to uni quizzes or anything, I've got my name on here, just genuinely trying to wrap my head around the difference between float and double. PS:我不是要问普通小测验或其他任何问题的答案,我的名字已经在这里了,只是真正地试图把我的头包裹在浮点数和双精度数之间。

Cheers, 干杯,

Chris. 克里斯。

A float is 4 bytes wide, whereas a double is 8 bytes wide. 浮点数为4字节宽,而双精度数为8字节宽。 You should probably prefer to use double in most cases. 在大多数情况下,您可能应该首选使用double。 You may check IEEE floating point standard. 您可以检查IEEE浮点标准。

Also to note that floats can be doubles, but doubles can never be floats because doubles have the larger range. 还要注意,浮点数可以是双精度数,但双精度数永远不能是浮点数,因为双精度数具有较大的范围。

Range of float is 1.40129846432481707e-45 to 3.40282346638528860e+38 浮动范围是1.40129846432481707e-45至3.40282346638528860e + 38

Range of double is 4.94065645841246544e-324d to 1.79769313486231570e+308d 精度范围是4.94065645841246544e-324d至1.79769313486231570e + 308d

Floats take less space, but at the cost of less precision (floats are 4 bytes, doubles are 8). 浮点数占用的空间较少,但代价是精度较低(浮点数为4字节,双精度数为8)。 It's the same reason you'd chose an int over a long. 这也是您长期以来选择int的原因。 Certain math operations might also be slower on doubles, but in practice, you probably want a double. 某些数学运算在double上也可能会变慢,但是在实践中,您可能想要double。

Generally float uses 4 bytes and double uses 8 bytes to store the value in a floating point (mantissa + exponent) format/representation. 通常,float使用4个字节,double使用8个字节以浮点(尾数+指数)格式/表示形式存储值。 See this wikepedia write-up for an intro to these concepts if you are interested: http://en.wikipedia.org/wiki/Floating_point 如果您有兴趣,请参阅以下wikepedia文章以获取这些概念的简介: http : //en.wikipedia.org/wiki/Floating_point

The only difference I know of is the precision, where float data type is a single precision 32-bit IEEE 754 floating point and double data type is a double precision 64-bit IEEE 754 floating point. 我知道的唯一区别是精度,其中float数据类型是单精度32位IEEE 754浮点,而double数据类型是双精度64位IEEE 754浮点。

Hope this helped you get a better understanding of the difference. 希望这可以帮助您更好地了解差异。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM