为什么两个浮点数之间的简单除法在java中不起作用?
System.out.println((26.55f/3f));
或
System.out.println((float)( (float)26.55 / (float)3.0 ));
等
返回结果 8.849999。不是应有的 8.85。
谁能解释一下这一点,或者我们都应该避免使用浮动?
System.out.println((26.55f/3f));
or
System.out.println((float)( (float)26.55 / (float)3.0 ));
etc.
returns the result 8.849999. not 8.85 as it should.
Can anyone explain this or should we all avoid using floats?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
每个程序员都应该了解的浮点运算知识:
链接网站上的深入解释
What Every Programmer Should Know About Floating-Point Arithmetic:
In-depth explanations at the linked-to site
查看维基百科关于浮点的文章,特别是精度问题部分。
本文提供了几个示例,应该可以让您更加清晰。
Take a look at Wikipedia's article on Floating Point, specifically the Accuracy Problems section.
The article features a couple examples that should provide more clarity.
解释很简单:浮点是一种二进制格式,因此只能精确表示某些自然整数
N
1.0 /(2 的 N 次方) 的整数倍的值>。26.55
没有这个属性,因此无法准确表示。如果您需要精确的表示(例如,您的代码是关于会计和金钱的,其中每一美分的一小部分都很重要),那么您确实必须避免浮动,而选择其他类型来保证您需要的值的精确表示(取决于您的应用程序) ,例如,仅以整数美分进行所有会计就足够了)。浮点数(如果使用得当且谨慎的话!-)非常适合工程和科学计算,其中输入值在任何情况下都不会“无限精确”,因此精确表示的计算繁琐负担绝对不值得承担。
Explaining is easy: floating point is a binary format and so can only represent exactly values that are an integer multiple of
1.0 / (2 to the Nth power)
for some natural integerN
.26.55
does not have this property, therefore it cannot be represented exactly.If you need exact representation (e.g. your code is about accounting and money, where every fraction of a cent matters), then you must indeed avoid floats in favor of other types that do guarantee exact representation of the values you need (depending on your application, for example, just doing all accounting in terms of integer numbers of cents might suffice). Floats (when used appropriately and advisedly!-) are perfectly fine for engineering and scientific computations, where the input values are never "infinitely precise" in any case and therefore the computationally cumbersome burden of exact representation is absolutely not worth carrying.
好吧,我们都应该在现实的情况下避免使用浮动,但那是另一天的故事了。
问题是浮点数无法准确表示我们认为在表示中微不足道的大多数数字。 8.850000 可能无法用浮点数精确表示;也可能不是两倍。这是因为它们实际上不是十进制数;而是十进制数。而是二进制表示。
Well, we should all avoid using floats wherever realistic, but that's a story for another day.
The issue is that floating point numbers cannot exactly represent most numbers we think of as trivial in presentation. 8.850000 probably cannot be represented exactly by a float; and possibly not by a double either. This is because they aren't actually decimal numbers; but a binary representation.