我正在编写一个应用程序,它使用十进制数进行大量操作(例如57.65).由于乘法和除法很快会削弱它们的准确性,我想将这些数字存储在一个类中,这个类在操作后保持它们的准确性,而不是依赖于float和double.
我在谈论这样的事情:
class FloatingPointNumber {
private:
long m_mantissa;
int m_dps; // decimal points
// so for example 57.65 would be represented as m_mantissa=5765, m_dps=2
public:
// Overloaded function for addition
FloatingPointNumber operator+(FloatingPointNumber n);
// Other operator overloads follow
}
Run Code Online (Sandbox Code Playgroud)
虽然我可以编写这样的类,但感觉有点像重新发明轮子,我确信必须有一些库类可以做到这一点(尽管STL中似乎不存在).
有人知道这样的图书馆吗?非常感谢.
你的意思是这样的吗?
#include "ttmath/ttmath.h"
#include <iostream>
int main()
{
// bigdouble consists of 1024*4 bytes for the mantissa
// and 256*4 bytes for the exponent.
// This is because my machine is 32-bit!
typedef ttmath::Big<1024, 256> bigdouble; // <Mantissa, Exponent>
bigdouble x = 5.05544;
bigdouble y = "54145454.15484854120248541841854158417";
bigdouble z = x * y * 0.01;
std::cout << z;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
您可以指定数量的机器字的尾数和指数只要你喜欢.我使用TTMath来解决Project Euler难题,我对它非常满意.我认为这是相对稳定的,如果你有疑问,作者非常友好.
编辑::我过去也使用过MAPM.它表示基数为100的大浮点数,因此将十进制数转换为基数为100将没有问题,与基数2不同.TTMAT使用基数2来表示大浮点数.自图书馆页面声称,它自2000年以来一直保持稳定.它已在许多应用程序中使用,您可以在库页面中看到它.它是一个带有漂亮的C++包装器的C库.
MAPM nextPrime(){
static MAPM prime = 3;
MAPM retPrime = prime;
prime += 2;
while( isPrime( prime ) == false )
prime += 2;
return retPrime;
}
Run Code Online (Sandbox Code Playgroud)
顺便说一句,如果你有兴趣在GMP和你正在使用VS,那么你可以检查MPIR这是GMP端口的Windows;)对我来说,我觉得TTMath比赏心悦目,更容易/比所有的东西我想是因为该库确实快了堆栈分配,无论如何都不会触及堆.基本上它不是一个任意的精度库,你在编译时指定精度,如上所示.