如何计算 int 和 float 的乘积超过 Int32/64 的限制?
How to have a calculation over the limits of Int32/64 for the product of an int and a float?
我的应用程序必须处理大数计算。如何将 int 和 float 相乘并获得 BigInteger 的乘积而不会溢出?具体来说,我必须得到 "BaseCost" x ("multiplier" by the power of "level")
我测试了“new BigInteger(100000000000000000000000)
”不起作用。所以我认为“if(BigInteger > (BigInteger)(Int1 * float1))
”行不通。它可能会在“(Int1 * float1)
”部分溢出。
这就是我解决问题的方法。我在 GitHub 中使用了来自 JcBernack 的 BigDecimal,这是以下代码。
private BigInteger Example
{
get
{
return (BigInteger)(new BigDecimal(Int1) * Float2);
}
}
我使用了 BigDecimal class,因为我无法将 BigInteger 与浮点数相乘。此外,在使用 class 之前,我确保添加了一个 BigInteger 施法器(来自 uhDreamer 的评论)。
public static explicit operator BigInteger(BigDecimal value)
{
BigDecimal floored = value.Floor();
return floored.Mantissa * BigInteger.Pow(10, floored.Exponent);
}
还有一个 Int 构造函数。
public BigDecimal(int t)
{
Exponent = 0;
Mantissa = t;
Normalize();
if(AlwaysTruncate)
{
Truncate();
}
}
现在,对于只需要整数相乘的开发人员,他们可以这样做 Int1(BigInteger) * Int2
。
当然,不要忘记 System.Numerics 命名空间。
我的应用程序必须处理大数计算。如何将 int 和 float 相乘并获得 BigInteger 的乘积而不会溢出?具体来说,我必须得到 "BaseCost" x ("multiplier" by the power of "level")
我测试了“new BigInteger(100000000000000000000000)
”不起作用。所以我认为“if(BigInteger > (BigInteger)(Int1 * float1))
”行不通。它可能会在“(Int1 * float1)
”部分溢出。
这就是我解决问题的方法。我在 GitHub 中使用了来自 JcBernack 的 BigDecimal,这是以下代码。
private BigInteger Example
{
get
{
return (BigInteger)(new BigDecimal(Int1) * Float2);
}
}
我使用了 BigDecimal class,因为我无法将 BigInteger 与浮点数相乘。此外,在使用 class 之前,我确保添加了一个 BigInteger 施法器(来自 uhDreamer 的评论)。
public static explicit operator BigInteger(BigDecimal value)
{
BigDecimal floored = value.Floor();
return floored.Mantissa * BigInteger.Pow(10, floored.Exponent);
}
还有一个 Int 构造函数。
public BigDecimal(int t)
{
Exponent = 0;
Mantissa = t;
Normalize();
if(AlwaysTruncate)
{
Truncate();
}
}
现在,对于只需要整数相乘的开发人员,他们可以这样做 Int1(BigInteger) * Int2
。
当然,不要忘记 System.Numerics 命名空间。