从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
所以 mpf_class
的问题不在 operator<<
重载 . 问题不仅存在于初始化,也存在于分配中 .
目前我使用以下内容:
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
1 回答
如果以相同的精度打印出双精度,你应该看到同样奇怪的数字 . 那只是因为0.1 can't be accurately represented in floating point . mpf_class正确地再现存储在double中的值 . 它's the double that isn' t符合您的期望 .
可能有一种方法可以指定gmp的精度或某种方式来舍入输入 . 我不知道在哪里看 .
Edit
mpf_class
有一个带有精度参数的构造函数:http://www.gnu.org/software/gmp/manual/html_node/C---Interface-Floats.html