使用 GCC 和 C++11 实施类型 "long double"

Implementation of type "long double" with GCC and C++11

本文关键字:类型 long double GCC C++11 施类型 使用      更新时间:2023-10-16

我尝试搜索有关长双精度的信息,到目前为止,我知道编译器以不同的方式实现它。

在 Ubuntu (XUbuntu) Linux 12.10 上使用 GCC 时,我得到这个:

double PId = acos(-1);
long double PIl = acos(-1);
std::cout.precision(100);
std::cout << "PId " << sizeof(double) << " : " << PId << std::endl;
std::cout << "PIl " << sizeof(long double)  << " : " << PIl << std::endl;

输出:

PId 8  : 3.141592653589793115997963468544185161590576171875
PIl 16 : 3.141592653589793115997963468544185161590576171875

有人明白为什么他们输出(几乎)相同的东西吗?

根据 acos 的引用,只有当你向它传递long double时,它才会返回一个long double。您还必须使用狒狒建议的std::acos。这对我有用:

#include <cmath>
#include <iostream>
int main() {
  double PId = acos((double)-1);
  long double PIl = std::acos(-1.0l);
  std::cout.precision(100);
  std::cout << "PId " << sizeof(double) << " :  " << PId << std::endl;
  std::cout << "PIl " << sizeof(long double)  << " : " << PIl << std::endl;
}

输出:

PId 8  : 3.141592653589793115997963468544185161590576171875
PIl 12 : 3.14159265358979323851280895940618620443274267017841339111328125
         3.14159265358979323846264338327950288419716939937510582097494459

最后一行不是输出的一部分,并且包含此精度的 pi 的正确数字。

要获得正确数量的有效数字,请使用 std::numeric_limits 。 在 C++11 中,我们对十进制有效数字进行了digits10(而不是给出有效digits)。

#include <cmath>
#include <iostream>
#include <limits>
int
main()
{
  std::cout.precision(std::numeric_limits<float>::digits10);
  double PIf = acos(-1.0F);
  std::cout << "PIf " << sizeof(float) << " :  " << PIf << std::endl;
  std::cout.precision(std::numeric_limits<double>::digits10);
  double PId = acos(-1.0);
  std::cout << "PId " << sizeof(double) << " :  " << PId << std::endl;
  std::cout.precision(std::numeric_limits<long double>::digits10);
  long double PIl = std::acos(-1.0L);
  std::cout << "PIl " << sizeof(long double)  << " : " << PIl << std::endl;
}

在x86_64 linux 上,我得到:

PIf 4 :  3.14159
PId 8 :  3.14159265358979
PIl 16 : 3.14159265358979324

尝试:

long double PIl = std::acos(-1.0L);

这使您传递一个长双精度,而不仅仅是一个被转换的 int。

请注意,无论如何,所有这些数字都是垃圾。使用 8 字节双精度,您将获得 15 个精度的数字,如果您将您的数字与实际 PI 进行比较

3.1415926535897932384626433

您会看到只有前 15 个数字适合。

如注释中所述,您可能不会获得双倍的精度,因为实现可能只使用 80Bit 表示形式,然后这取决于它为尾数保留了多少位。

相关文章: