长双sqrt()的准确性

Bre*_*and 4 c++ double sqrt long-integer

我注意到sqrt()的long double版本的准确性存在问题.以下代码演示了此问题.

#include <iostream>
#include <cmath>
#include <cfloat>

int main(int argc, char ** argv)
{
  int count=0;
  long double s=sqrt(3L);
  std::cout.precision(21);
  std::cout << "s=" << s << ", s^2=" << s*s << std::endl;
  while( s*s<3L+LDBL_EPSILON ) {
    s+=LDBL_EPSILON;
    std::cout << s << ' ' << s*s << std::endl;
    ++count;
  }
  std::cout << "sqrt(3L) is approximately " << count << " multiples of LDBL_EPSILON away from the correct value." << std::endl;
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

编译并运行它

>g++ -o sqrt sqrt.cpp && ./sqrt
Run Code Online (Sandbox Code Playgroud)

s=1.73205080756887719318, s^2=2.9999999999999996524
1.73205080756887719329 2.99999999999999965284
1.73205080756887719339 2.99999999999999965306
... (922 lines omitted)
1.73205080756887729347 2.99999999999999999978
1.73205080756887729357 3.00000000000000000022
sqrt(3L) is approximately 926 multiples of LDBL_EPSILON away from the correct value.
Run Code Online (Sandbox Code Playgroud)

sqrt()的常规double版本给出了最接近实际值的double.

我正在使用的g ++版本是

>g++ -v
Using built-in specs.
Target: x86_64-linux-gnu
Configured with: ../src/configure -v --with-pkgversion='Debian 4.4.5-8' --with-bugurl=file:///usr/share/doc/gcc-4.4/README.Bugs --enable-languages=c,c++,fortran,objc,obj-c++ --prefix=/usr --program-suffix=-4.4 --enable-shared --enable-multiarch --enable-linker-build-id --with-system-zlib --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --with-gxx-include-dir=/usr/include/c++/4.4 --libdir=/usr/lib --enable-nls --enable-clocale=gnu --enable-libstdcxx-debug --enable-objc-gc --with-arch-32=i586 --with-tune=generic --enable-checking=release --build=x86_64-linux-gnu --host=x86_64-linux-gnu --target=x86_64-linux-gnu
Thread model: posix
gcc version 4.4.5 (Debian 4.4.5-8) 
Run Code Online (Sandbox Code Playgroud)

这是一个已知的错误?我应该在某处报告吗?

Mar*_*k B 9

你在这里有两个问题:首先,3L隐含地提升到double不是long double这样,即使你将返回值分配给long double它仍然使用低精度版本sqrt.你需要以static_cast3 long double为参数.其次,只有double版本sqrt被导入全局命名空间,因为C中不支持函数重载,你必须使用std::sqrt.

从而:

long double s=std::sqrt(static_cast<long double>(3));

  • 无需演员:3.0L (3认同)