使用长双精度还是仅双精度来计算pi? [英] Using a long double or just a double for calculating pi?

查看:215
本文介绍了使用长双精度还是仅双精度来计算pi?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用长公式计算pi.我正在尝试更熟悉浮点数等.我有一个使用双精度的工作程序.我的代码存在的问题是:

I'm calculating pi using a long winded formula. I'm trying to get more familiar with floating point numbers etc. I have a working program that uses doubles. The problem with my code is:

  1. 如果我使用双精度数,则pi仅精确到小数点后第七位.我无法获得更准确的信息.
  2. 如果我使用长双精度数,则pi可以精确到小数点后9位,但是代码需要花费更长的时间才能运行.如果使用长双精度检查小于0.00000001的精度,则pi返回值9.4246775.我认为这是由于长双倍.

我的问题是什么是最准确的变量类型?如何更改代码以提高pi的精度?

My question is what is the most accurate variable type? How could I change my code to improve the precision of pi?

这是我的代码:

#include <iomanip>
#include <cstdlib>
#include <iostream>
#include <cmath>

using namespace std;

int main()
{
 double arctan;
 double pi;
 double precision;
 double previous=0;
 int y=3;
 int loopcount=0;

   cout<<"Start\n";

   arctan=1-(pow(1,y)/y);

 do
   {
     y=y+2;
     arctan=arctan+(pow(1,y)/y);
     y=y+2;
     arctan=arctan-(pow(1,y)/y);

      pi=4*(arctan);

    //  cout<<"Pi is: ";
    //  cout<<setprecision(12)<<pi<<endl;

      precision=(pi*(pow(10,10)/10));

      loopcount++;

      if(precision-previous<0.000000001)
        break;

      previous=precision;
    }
  while(true);

  cout<<"Pi is:"<<endl;
       cout<<setprecision(11)<<pi<<endl;
  cout<<"Times looped:"<<endl;
       cout<<loopcount<<endl;

return 0;
}

推荐答案

您可以从std :: numeric_limits

You can get the max limits of doubles/long doubles from std::numeric_limits

#include <iostream>
#include <limits>

int main()
{
    std::cout << "     Double::digits10:  " << std::numeric_limits<double>::digits10 << "\n";
    std::cout << "Long Double::digits10:  " << std::numeric_limits<long double>::digits10 << "\n";
}

在我的机器上,它给出:

On my machine this gives:

     Double::digits10:  15
Long Double::digits10:  18

因此,我希望long double可以精确到18位数字.
该术语的定义可以在这里找到:

So I expect long double to be accurate to 18 digits.
The definition of this term can be found here:

http://www.cplusplus.com/reference/std/limits/numeric_limits /

标准报价:18.3.2 Numeric limits [limits]

也请注意:由于注释在上面的列表中很低:

Also Note: As the comment is way down in the above list:

@sarnold在关于pow()的断言中是错误的(尽管神秘地他有两个愚蠢的人不加选择地投票赞成他的评论).他声明的内容仅适用于C.C++具有类型的重载,因为在C ++中,pow()是模板函数.请参阅: http://www.cplusplus.com/reference/clibrary/cmath/pow/26.4.7 complex value operations [complex.value.ops]

That @sarnold is incorrect (though mysteriously he has two silly people up-voting his comment without checking) in his assertions on pow(). What he states is only applicable to C. C++ has overloads for the types because in C++ pow() is a template function. See: http://www.cplusplus.com/reference/clibrary/cmath/pow/ in the standard at 26.4.7 complex value operations [complex.value.ops]

这篇关于使用长双精度还是仅双精度来计算pi?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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