从double初始化GMP浮点变量(mpf_t或mpf_class,无关紧要的正确方法是什么?
代码:
#include <iostream>
#include <gmpxx.h>
int main()
{
double d=0.1;
//1024 bits is more that 300 decimal digits
mpf_set_default_prec(1024);
mpf_class m(d);
//after initializing mpf_class variable, set default output precision
std::cout.precision(50);
std::cout.setf(std::ios_base::scientific);
std::cout << m << std::endl;
return 0;
}
输出为:
1.00000000000000005551115123125782702118158340454102e-01
如果我直接打印d
,但是在m
变量中,可以信任300个十进制尾数!我将GMP用于迭代数值方法,因此这些非零值会引入错误,并使方法收敛缓慢。
如果我将m
初始化为mpf_class m("0.1");
,则输出为:
1.00000000000000000000000000000000000000000000000000e-01
因此问题不在operator<<
的mpf_class
过载中。该问题不仅存在于初始化,而且也存在于分配。
目前我使用以下内容:
mpf_class linsys::DtoGMP(const double& arg)
{
char buf[512];
sprintf(buf,"%.15le\n",arg);
return mpf_class(buf);
}
为了正确的转换。
是否有更快和/或更本地化的方法?
我的操作系统是OpenSUSE 12.1,编译器:gcc 4.6.2
如果以相同的精度打印双精度数,则应该看到相同的看起来奇怪的数字。那是因为0.1 can't be accurately represented in floating point。 mpf_class准确地再现了存储在double中的值。这是不符合您期望的两倍。
可能有一种方法可以指定gmp的精度或某种舍入输入的方法。 我不确定该看哪里。
编辑
[mpf_class
具有带有精度参数的构造函数:http://www.gnu.org/software/gmp/manual/html_node/C---Interface-Floats.html
您可以使用此方法
mpf_class a;
double d=0.1;
a=static_cast<mpf_class>(d*10)/static_cast<mpf_class>(10);
如果您知道双精度数有多少小数位,可以使用他的方法