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

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

问题描述

这里有人可以帮助我了解如何确定浮点限制何时会导致计算错误.例如下面的代码.

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) 我实际上可以看到计算开始失去准确性的地方(小数点后第 6 位左右).尽管如此,我对浮点数的理解是,即使是很小的数字有时也无法表示或被我误解,并且可以始终准确表示 4 个小数位(例如).

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...

这意味着他们无法准确把握任何数量的表示不是二进制分数(形式为 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).

从根本上说,我的问题归结为这个.如何确定任何特定方法是否容易出现浮点运算中的错误,这些错误会以什么精度出现,以及需要哪些输入来产生这些错误?

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.

推荐答案

从阅读每个计算机科学家应该知道的关于浮点数的内容开始:http://docs.sun.com/source/806-3568/ncg_goldberg.html

简短回答:双精度浮点数(这是 JavaScript 中的默认值)具有大约 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).

但如果足以得到高精度的答案,浮点数应该足够好,尤其是双精度.

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天全站免登陆