如何在C 中找到具有20位精度的平方根

How to find square root with 20 digit precision in C++?

本文关键字:20位 精度 平方根      更新时间:2023-10-16

嗨,大家好,我一直坚持这项作业,我需要使用 bisection方法 precision 10^-20 aka 0.0000000000000000000001找到方程的根我虽然是因为我没有使用长double,也没有在数字结束时使用l,但是即使我使用它,我的最后3位数字也不正确,对于下面给出的代码,我要求您给您提供数字我的案例为5,所以我得到2.3227751229355622087

正确的答案应为2.3227751229355622988,但我真的找不到我的错误,但如果某些人帮助我解决这个问题,我会很高兴。

供您参考,以下是二等方法的描述和插图

这是我的代码:

#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;
 }

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

安装另一个编译器后,20位数精度没有任何问题。随着我进行的更多调查,似乎有些编译器在十进制之后的限制为14或15。如果C 拒绝将您的号码舍入更高的精度,则更改编译器:)