从Codeplex获得BigRational。它是微软的Base Class Library的一部分,因此它是.Net的一项工作。一旦你的,然后做一些事情,如:
System.Numerics.BigInteger x = GetDividend() ;
System.Numerics.BigInteger y = GetDivisor() ;
BigRational r = new BigRational(x , y) ;
double value = (double) r ;
与必然溢/下溢/的精度,当然,另一个问题损失的处理。
既然你不能在BigRational库拖放到你的代码,显然,其他的办法是走出right algorithms book并推出自己的...
最简单的方法,当然,滚动”自己的“,因为有理数表示为两个整数的比率(除法),是从BigRational类抓取显式转换为双运算符并调整它以适应。我花了大约15分钟。
关于我所做的唯一重大修改是当结果为正数或负数零/无穷时,结果的符号如何设置。当我在它时,我将它转换为BigInteger
扩展方法为您:
public static class BigIntExtensions
{
public static double DivideAndReturnDouble(this BigInteger x , BigInteger y)
{
// The Double value type represents a double-precision 64-bit number with
// values ranging from -1.79769313486232e308 to +1.79769313486232e308
// values that do not fit into this range are returned as +/-Infinity
if (SafeCastToDouble(x) && SafeCastToDouble(y))
{
return (Double) x/(Double) y;
}
// kick it old-school and figure out the sign of the result
bool isNegativeResult = ((x.Sign < 0 && y.Sign > 0) || (x.Sign > 0 && y.Sign < 0)) ;
// scale the numerator to preseve the fraction part through the integer division
BigInteger denormalized = (x * s_bnDoublePrecision)/y ;
if (denormalized.IsZero)
{
return isNegativeResult ? BitConverter.Int64BitsToDouble(unchecked((long)0x8000000000000000)) : 0d; // underflow to -+0
}
Double result = 0 ;
bool isDouble = false ;
int scale = DoubleMaxScale ;
while (scale > 0)
{
if (!isDouble)
{
if (SafeCastToDouble(denormalized))
{
result = (Double) denormalized;
isDouble = true;
}
else
{
denormalized = denormalized/10 ;
}
}
result = result/10 ;
scale-- ;
}
if (!isDouble)
{
return isNegativeResult ? Double.NegativeInfinity : Double.PositiveInfinity;
}
else
{
return result;
}
}
private const int DoubleMaxScale = 308 ;
private static readonly BigInteger s_bnDoublePrecision = BigInteger.Pow(10 , DoubleMaxScale) ;
private static readonly BigInteger s_bnDoubleMaxValue = (BigInteger) Double.MaxValue;
private static readonly BigInteger s_bnDoubleMinValue = (BigInteger) Double.MinValue;
private static bool SafeCastToDouble(BigInteger value)
{
return s_bnDoubleMinValue <= value && value <= s_bnDoubleMaxValue;
}
}
您需要它有多精确? – 2012-08-08 20:14:48
你正在处理的数字是什么。请显示数字的性质。 – MethodMan 2012-08-08 20:16:13
@AustinSalonen:精度越高越好,但即使精确到几位十进制数字也足以达到我想要的位置。 – 2012-08-08 20:20:11