【发布时间】:2014-01-25 20:21:32
【问题描述】:
我已将 Clipper library 的实验性 C#“浮动”版本翻译为 javascript。在最新的沙盒版本中,有一个函数IsAlmostEqual 似乎很难翻译。由于数值稳定性问题,无法使用 == 运算符比较双重相等,因此需要此函数来处理这些问题。
-9223372036854775808 - aInt 和 -9223372036854775808 - bInt 很容易使用例如计算BigInteger 库,但BitConverter.DoubleToInt64Bits 更难。
知道如何将IsAlmostEqual 函数翻译成javascript吗?或者具体如何实现BitConverter.DoubleToInt64Bits到javascript?
private static bool IsAlmostEqual(double A, double B)
{
//http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm
Int64 aInt = BitConverter.DoubleToInt64Bits(A);
if (aInt < 0) aInt = unchecked(-9223372036854775808 - aInt);
Int64 bInt = BitConverter.DoubleToInt64Bits(B);
if (bInt < 0) bInt = unchecked(-9223372036854775808 - bInt);
return (Math.Abs(aInt - bInt) <= 10000000000);
}
数值稳定性和鲁棒性:
http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm
http://www.mpi-inf.mpg.de/~kettner/pub/nonrobust_cgta_06.pdf
http://cpc.cs.qub.ac.uk/MRSN/higham.pdf
http://www.2ality.com/2012/04/number-encoding.html
【问题讨论】:
标签: c# javascript numerical-stability