c++ - 将 double 精确转换为 mpf_class

标签 c++ gmp

从 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

最佳答案

如果您以相同的精度打印 double ,您应该会看到相同的奇怪数字。那只是因为 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

关于c++ - 将 double 精确转换为 mpf_class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13663146/

相关文章:

c++ - 获取当前的旋转和位置坐标

c++ - 使用 gmp 在 C++ 中编译代码时出错

c++ - Visual Studio 构建错误 : unresolved external symbol _IID_IWICImagingFactory (MFC static lib)

c++ - 查找数组中最大数的有效方法

c++ - 如何使用GMP生成一定范围内的随机数

用于 Diffie-Hellman key 交换的 C++ GMP 随机数生成

c++ - 结合 GMPXX 和 C++11 及更高版本

linux - 在 Alpine 上从源代码安装 GCC

c++ - 如何全局捕获 X11 中的每一次鼠标点击?

c++ - Qt/C++ - "Including"头文件导致大量错误(垃圾邮件)