长双倍输出的精度不正确.可能是什么问题? [英] The precision of the long double output is not correct. What might be wrong?

查看:88
本文介绍了长双倍输出的精度不正确.可能是什么问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个long double常量,我将其设置为const或not-const.它比我的测试工作站上的long double的精度(19位)长(40位).

I have a long double constant that I am setting either as const or not-const. It is longer (40 digits) than the precision of a long double on my test workstation (19 digits).

当我打印出来时,它不再以19位精度显示,而是以16位精度显示.

When I print it out, it no longer is displayed at 19 digits of precision, but at 16.

这是我正在测试的代码:

Here is the code I am testing:

#include <iostream>
#include <iomanip>
#include <limits>
#include <cstdio>

int main ()
{
    const long double constLog2 = 0.6931471805599453094172321214581765680755;
    long double log2 = 0.6931471805599453094172321214581765680755;    

    std::cout << std::numeric_limits<long double>::digits10 + 1 << std::endl;
    std::cout << "const via cout: " << std::setprecision(19) << constLog2 << std::endl;
    std::cout << "non-const via cout: " << std::setprecision(19) << log2 << std::endl;
    std::fprintf(stdout, "const via printf: %.19Lf\n", constLog2);
    std::fprintf(stdout, "non-const via printf: %.19Lf\n", log2);

    return 0;
}

编译:

$ g++ -Wall precisionTest.cpp

输出:

$ ./a.out
19
const via cout: 0.6931471805599452862
non-const via cout: 0.6931471805599452862
const via printf: 0.6931471805599452862
non-const via printf: 0.6931471805599452862

我希望0.6931471805599453094,但得到0.6931471805599452862.

将19位精度降低到16位是有原因的吗?

Is there a reason that the 19 digits of precision are cut to 16 digits?

这是我的环境:

$ gcc --version
i686-apple-darwin9-g++-4.0.1 (GCC) 4.0.1 (Apple Inc. build 5490)

我在其他版本的gcc上遇到了同样的问题,例如:

I am seeing the same problem with other versions of gcc, e.g.:

$ gcc --version
g++ (GCC) 3.4.6 20060404 (Red Hat 3.4.6-10)

我可以查看NTL或其他库,但是我很好奇是什么原因造成的.感谢您的见识.

I can look into NTL or other libraries but I'm curious what is causing this. Thanks for your insight.

推荐答案

我得到以下输出:

19
const via cout: 0.6931471805599453094
non-const via cout: 0.6931471805599453094
const via printf: 0.6931471805599453094
non-const via printf: 0.6931471805599453094

但是我使用的是长双字面量而不是双字面量:

But i'm using long double literals instead of double literals:

const long double constLog2 = 0.6931471805599453094172321214581765680755L;
long double log2 = 0.6931471805599453094172321214581765680755L;    

这篇关于长双倍输出的精度不正确.可能是什么问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆