System.Numerics.BigInteger允许将大整数相乘,但是浮点数有相同类型的吗?如果没有,有没有免费的库可以使用?
//this but with floats
System.Numerics.BigInteger maxint = new BigInteger(int.MaxValue);
System.Numerics.BigInteger big = maxint * maxint * maxint;
System.Console.WriteLine(big);发布于 2012-04-28 08:16:43
也许你在找BigRational?微软在CodePlex上的BCL项目下发布了它。实际上不确定它如何或是否适合您的需求。
它将其保持为有理数。您可以通过强制转换或某些乘法来获得带有小数值的字符串。
var r = new BigRational(5000, 3768);
Console.WriteLine((decimal)r);
Console.WriteLine((double)r);或者使用像这样的简单(Ish)扩展方法:
public static class BigRationalExtensions
{
public static string ToDecimalString(this BigRational r, int precision)
{
var fraction = r.GetFractionPart();
// Case where the rational number is a whole number
if(fraction.Numerator == 0 && fraction.Denominator == 1)
{
return r.GetWholePart() + ".0";
}
var adjustedNumerator = (fraction.Numerator
* BigInteger.Pow(10, precision));
var decimalPlaces = adjustedNumerator / fraction.Denominator;
// Case where precision wasn't large enough.
if(decimalPlaces == 0)
{
return "0.0";
}
// Give it the capacity for around what we should need for
// the whole part and total precision
// (this is kinda sloppy, but does the trick)
var sb = new StringBuilder(precision + r.ToString().Length);
bool noMoreTrailingZeros = false;
for (int i = precision; i > 0; i--)
{
if(!noMoreTrailingZeros)
{
if ((decimalPlaces%10) == 0)
{
decimalPlaces = decimalPlaces/10;
continue;
}
noMoreTrailingZeros = true;
}
// Add the right most decimal to the string
sb.Insert(0, decimalPlaces%10);
decimalPlaces = decimalPlaces/10;
}
// Insert the whole part and decimal
sb.Insert(0, ".");
sb.Insert(0, r.GetWholePart());
return sb.ToString();
}
}如果超出了decimal或double的精度范围,它们将被转换为各自的值为0.0的类型。此外,当结果超出其范围时,强制转换为decimal将导致抛出OverflowException。
我编写的扩展方法(这可能不是计算分数小数表示的最好方法)将以无限的精度准确地将其转换为字符串。但是,如果数字小于请求的精度,它将返回0.0,就像decimal或double一样。
发布于 2020-11-27 14:47:43
应该考虑如果有BigFloat类型会有什么影响。
BigFloat x = 1.0;
BigFloat y = 3.0;
BigFloat z = x / y;答案是0.333333333333333333333333333333333333333333333333333333递归。永远不变。无限的。内存不足错误。
构造无限的BigFloat是很容易的。
但是,如果您乐于使用有理数,即用一个整数除以另一个整数来表示的有理数,那么您可以使用BigInteger来构建一个BigRational类型,该类型可以为表示任何实数提供任意精度。
BigRational x = 1;
BigRational y = 3;
BigRational z = x / y;这是有效的,并给我们提供了这样的类型:

你可以只使用NuGet BigRational,你会发现很多实现,包括一个来自微软的。
https://stackoverflow.com/questions/10359372
复制相似问题