繁体   English   中英

如何在C ++中以20位精度查找平方根?

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

嗨,大家好,我忙于这项作业,我需要使用精确度为10 ^ -20的Bisection方法找到方程的根,所以起初我虽然是因为我没有使用长整型,最后也使用了L的数字,但是即使我使用它,我的最后3位数字也不正确,因为下面给出的代码要求您在我的情况下给a的数字是5,所以我得到2.32277512293556220220

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

供您参考,这是Bisection方法的描述和说明

这是我的代码:

#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 ++拒绝将您的数字舍入为更高的精度,请更改编译器:)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM