为什么存储在Float数据类型中的数据被认为是一个近似值? [英] Why is the data stored in a Float datatype considered to be an approximate value?

查看:300
本文介绍了为什么存储在Float数据类型中的数据被认为是一个近似值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从来没有明白为什么浮点数据类型被认为是一个近似值,而十进制数据类型被认为是确切的。我正在寻找一个很好的解释,谢谢。

解决方案

嗯,你是对的 - 做这样的毯子是误导性的声明。要完全理解你需要把握两件事情。首先,小数旨在存储(精确地)具有固定小数位数的十进制值。通常是钱(例如小数点是美分)。这是一个非常具体的用例。它不是一个确切的存储任何值;它只适用于具有固定小数点数的十进制数值,而实现则是为了做到这一点而设计的。第二,浮点数应该是一个更通用的数据类型 - 它们被用来存储任何价值 - 实施反映了这一点(所以,例如,实施的目标是尽可能有效地覆盖广泛的范围和支持操作)。特别是,它使用了一个二进制表示,不能完全表示所有十进制值。所以,例如,它可以精确地存储0.5,但不能精确地存储0.1。这只是一个二进制基础2表示法的一个事实,但这意味着对于金钱来说,浮点数不是一个好主意:如果你不能精确地存储0.10浮点数,那么涉及10美分的任何计算都可能会累积到意想不到的错误。换句话说,两者都有其局限性。小数点比浮点数更精确的唯一方法就是更容易理解:精确定义的值是明确定义的,有用的,并且与我们使用的自然基数表示相匹配。相比之下,理解哪些值完全由浮点数存储,哪些不依赖于浮点数,因为它们依赖于基础的基表示形式,要难得多。

I've never understood why a float datatype is considered an approximation while a decimal datatype is considered exact. I'm looking for a good explanation, thanks.

解决方案

well, you're right - it's misleading to make such a blanket statement. to understand completely you need to grasp two things.

first, decimal is intended for storing (exactly) decimal values with a fixed number of decimal places. typically, money (where the decimals are cents, for example). that's a very specific use case. it's not an exact store for any value; it's only for decimal values with a fixed number of decimal points, and the implementation is tailored to do that correctly.

second, floats are intended to be a more general datatype - they are used to store "any" value - and the implementation reflects that (so, for example, the implementation aims to cover a wide range of scales and support operations as efficiently as possible). in particular, it uses a binary representation that cannot represent all decimal values exactly. so, for example, it can store 0.5 exactly, but it can't store 0.1 exactly. that's just a fact of life of the binary - base 2 - representation used, but it means that for money, floats are not a good idea: if you can't store 0.10 exactly as a float then any calculations involving 10 cents may accumulate unexpected errors.

in other words, both have their limitations. the only way that decimal is "more exact" than float is that it's easier to understand: the values for which it does work exactly are clearly defined, useful, and match the "natural" base 10 representation we use. in contrast, it's much harder to understand which values will be stored exactly by floats, and which not, because they depend on the underlying base 2 representation.

这篇关于为什么存储在Float数据类型中的数据被认为是一个近似值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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