了解浮点问题 [英] Understanding floating point problems

查看:131
本文介绍了了解浮点问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能有人在这里请帮助我了解如何确定何时浮点限制将在你的计算导致错误。例如,下面的code。

Could someone here please help me understand how to determine when floating point limitations will cause errors in your calculations. For example the following code.

CalculateTotalTax = function (TaxRate, TaxFreePrice) {
     return ((parseFloat(TaxFreePrice) / 100) * parseFloat(TaxRate)).toFixed(4);
};

我一直无法投入已经造成对我来说这种方法不正确结果的任何两个值。如果我删除toFixed(4)我可以INFACT看到计算开始失去准确度(大约6号小数位的地方)。话虽如此,虽然,我彩车的理解是,即使是很小的数字,有时无法重新presented或者我误解和CAN小数点后4位(例如)总是被重新准确psented $ P $。

I have been unable to input any two values that have caused for me an incorrect result for this method. If I remove the toFixed(4) I can infact see where the calculations start to lose accuracy (somewhere around the 6th decimal place). Having said that though, my understanding of floats is that even small numbers can sometimes fail to be represented or have I misunderstood and can 4 decimal places (for example) always be represented accurately.

MSDN解释花车为这样 ...

MSDN explains floats as such...

这意味着他们不能确切持有
  再是任何数量的presentation
  不是二进制小数(形式的k /
  (2 ^ n),其中k和n是整数)

This means they cannot hold an exact representation of any quantity that is not a binary fraction (of the form k / (2 ^ n) where k and n are integers)

现在我认为这适用于所有的花车(计有那些在JavaScript中使用)。

Now I assume this applies to all floats (inlcuding those used in javascript).

从根本上说,我的问题归结到这一点。怎样才能和确定是否有任何具体的方法将容易受到浮点运算错误,在将这些错误兑现什么precision将需要什么样的输入,产生这些错误?

Fundamentally my question boils down to this. How can one determine if any specific method will be vulnerable to errors in floating point operations, at what precision will those errors materialize and what inputs will be required to produce those errors?

希望什么,我问是有道理的。

Hopefully what I am asking makes sense.

推荐答案

阅读开始的什么每台计算机科学家应该知道关于浮点的:
<一href=\"http://docs.sun.com/source/806-3568/ncg_goldberg.html\">http://docs.sun.com/source/806-3568/ncg_goldberg.html

简短的回答:双precision花车(这是在JavaScript中默认的)有precision的约16位十进制数字。四舍五入可以改变因平台。如果是,你得到一贯正确的答案绝对必要的,你应该做你自己理性的算术(这并不需要是硬 - 货币,也许你可以乘100美分的号码存储为一个整数)。

Short answer: double precision floats (which are the default in JavaScript) have about 16 decimal digits of precision. Rounding can vary from platform to platform. If it is absolutely essential that you get the consistently right answer, you should do rational arithmetic yourself (this doesn't need to be hard - for currency, maybe you can just multiply by 100 to store the number of cents as an integer).

但是,如果它足以获得具有高度precision的答案,花车应该足够好,特别是双precision。

But if it suffices to get the answer with a high degree of precision, floats should be good enough, especially double precision.

这篇关于了解浮点问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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