【问题标题】:How to find square root with 20 digit precision in C++?如何在 C++ 中找到 20 位精度的平方根?
【发布时间】:2016-12-06 16:13:21
【问题描述】:

大家好,我坚持做这个作业,我需要使用 二分法 找到方程的根,精度为 10^-20 又名 0.000000000000000000001 所以起初我认为这是因为我不是t 在数字末尾使用 long double 和 L ,但是即使我使用它,我的最后 3 位数字也不正确,因为下面给出的代码要求您提供 a 在我的情况下的数字是 5 ,所以我得到 2.3227751229355622087

虽然正确答案应该是 2.3227751229355622988,但我真的找不到我的错误,如果有人能帮助我解决这个问题,我会很高兴。

以下是Bisection method的描述和插图,供您参考

这是我的代码:

#include<iostream>
#include<cmath>
#include<math.h>
#include<iomanip>

using namespace std;

long double f(long double   x, long double a);
long double F = 123456L % 100L;

long double f(long double  x, long double a)
{
    long double  sum = pow(x, 5) - a*x - F;
    return sum;
}

int main()
{
    cout.setf(ios::fixed);
    long double a, b, c, fa, fb, fc;
    long double e;
    long double aa;
    bool flag = true;
    while (cin >> aa)
    {
        cout.precision(19);
        flag = true;
        a = 0L;
        b = 10L;
        e = 0.00000000000000000001L;

        if (f(a, aa)*f(b, aa)>0)
        {
            flag = false;
        }

        while(fabs(a-b)>=e){
            c = (a + b) / 2.0L;
            fa = f(a, aa);
            fb = f(b, aa);
            fc = f(c, aa);

            if (fc == 0)
            {       
                break;
            }

            if (fa*fc>0)
            {
                a = c;
            }
            else if (fa*fc<0)
            {
                b = c;
            }
        } 

        if (flag == true)
        {
            cout  << c << endl;
        }
        else 
        {
            cout << "NO SOLUTION" << endl;
        }
    }
    return 0;
 }

【问题讨论】:

标签: c++ math precision


【解决方案1】:

问题是我使用了错误的编译器 (Visual Studio)。

安装另一个编译器后,20 位精度没有任何问题。当我进行更多调查时,似乎某些编译器在小数点后限制为 14 或 15。 如果 c++ 拒绝将您的数字四舍五入到更高的精度,请更改编译器:)

【讨论】:

  • 您的问题与 C++ 或编译器无关,而与数字的表示方式有关。
  • 也许但它仍然是一个 VS 问题,因为在我用另一个不会自动打开应用程序的程序编译它之后,然后我运行 exe 一切都按预期工作。跨度>
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-27
  • 2014-03-03
  • 2015-07-26
  • 2013-02-02
相关资源
最近更新 更多