c++ - 将 2 个大于 long double 最大限制的数字相乘

标签 c++ c

如何将两个大于最大限制的数字相乘,即 1.89731e+4932long double使用 C++/C 例如。 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)

关于c++ - 将 2 个大于 long double 最大限制的数字相乘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18031381/

相关文章:

c - 使用 NI VISION imaqDetectLines() 函数时出现一般保护错误

c - 非可移植指针转换

c - 设计交互式客户端

c - 从 C 中的函数返回字符串

c - 如何将堆栈跟踪中的符号名称存储在 GDB 脚本变量中?

c++ - 冲突 std::set 和 NTL::vec_ZZ

c++ - 在主函数之前声明具有用户定义大小的数组

c++ - 基本 Qt 应用程序 : Reports Masive Leaks 上的 Valgrind

c++ - 在 C++ 中将重写的类方法作为链调用

c++ - 双向插入排序错误