gpt4 book ai didi

c# - C# 中有 BigFloat 类吗?

转载 作者:太空狗 更新时间:2023-10-29 18:13:38 26 4
gpt4 key购买 nike

System.Numerics.BigInteger 可让您将大整数相乘,但是否有相同类型的 float ?如果没有,是否有我可以使用的免费图书馆?

//this but with floats
System.Numerics.BigInteger maxint = new BigInteger(int.MaxValue);

System.Numerics.BigInteger big = maxint * maxint * maxint;
System.Console.WriteLine(big);

最佳答案

也许您正在寻找 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。此外,转换为十进制,当结果超出其范围时,将导致抛出 OverflowException

我写的扩展方法(这可能不是计算分数的小数表示的最佳方法)会准确地将它转换为字符串,精度不受限制。但是,如果数字小于要求的精度,它将返回 0.0,就像 decimal 或 double 一样。

关于c# - C# 中有 BigFloat 类吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10359372/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com