可以使用浮点数据类型来存储确切的数字吗? [英] Can floating-point data types be used to store exact numbers at all?

查看:152
本文介绍了可以使用浮点数据类型来存储确切的数字吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我直接(不是计算结果),请将0.0001显式分配给一个Double类型的变量,它是否保证完全等于0.0001,无论它在哪里?

If I directly (not getting it as a result of a calculation), explicitly assign 0.0001 to a variable of a Double type, is it guaranteed to be exactly equal to 0.0001 wherever it goes?

推荐答案

不,因为不能将0.0001表示为(有限)二进制分数 - 当文字被编译或解释时,你会得到一个四舍五入的错误。

No... because it's simply impossible to represent 0.0001 as a (finite) binary fraction - you'll get a rounding error when the literal is compiled or interpreted.

整数可以存储而不舍入 - 达到精度限制,当然要比同类大小的整数类型小。当达到极限时,而不是溢出,您开始失去精度,因此在某些时候 d == d + 1

However, integer numbers can be stored without rounding - up to the limit of precision, which is of course lower than for an integer type of the same size. And when the limit is reached, instead of an overflow, you start to lose precision, so at some point d == d+1

这篇关于可以使用浮点数据类型来存储确切的数字吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆