乘以两个大于长双的最大限制的数字

multiply 2 numbers that are bigger than maximum limit of long double

本文关键字:数字 大于 两个      更新时间:2023-10-16

如何使用C++/C将大于最大极限的两个数字相乘,即long double1.89731e+4932,例如2.79654E+256783.89574e+35890。。。

有两种可能性(C#示例):

您可以使用BigInteger(在您的情况下,它似乎效率低下,但使用高精度数字很方便)

BigInteger a = 279654 * BigInteger.Pow(10, 25678 - 5); // <- 2.79654E25678 = 279654E25678 * 1E-5
BigInteger b = 389574 * BigInteger.Pow(10, 35890 - 5); // <- 3.89574E35890 = 389574E35890 * 1E-5
BigInteger result = a * b;

您可以分别操作尾数和指数:

Double mantissaA = 2.79654;
int exponentA = 25678;
Double mantissaB = 3.89574;
int exponentB = 35890;
Double mantissaResult = mantissaA * mantissaB;
int exponentResult = exponentA + exponentB;
// Let's adjust mantissaResult, it should be in [1..10) (10 is not included) range
if ((mantissaResult >= 10) || (mantissaResult <= -10)) { 
  mantissaResult /= 10.0 
  exponentResult += 1; 
}
else if (((mantissaResult < 1) && (mantissaResult > 0)) || ((mantissaResult > -1) && (mantissaResult < 0)))  {
  mantissaResult *= 10.0 
  exponentResult -= 1;  
}
// Let's output the result
String result = mantissaResult.ToString() + "E+" + exponentResult.ToString();

附言:通常在乘法的情况下,使用对数和加法更方便:

A * B -> Log(A) + Log(B)