简体   繁体   中英

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

Hi guys I'm stuck with this homework where I need to find the root of equation using Bisection method with precision 10^-20 aka 0.00000000000000000001 so at first I though it was cause I wasn't using long double and also L at the end of the numbers, however even when I use it my last 3 digits are not correct, for the code that is given below ask you to give the number for a in my case is 5 , so I get 2.3227751229355622087

while the correct answer should be 2.3227751229355622988, I really can't find my mistake , will be happy if some1 assist me with this problem.

For your reference, here's a description and illustration of the Bisection method .

Here's my code:

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

The problem was that I was using the wrong compiler (Visual Studio).

As soon as installed another compiler, there wasn't any problem with the 20 digit precision. As I investigated more, it appears that some compilers have a limit after the decimal to 14 or 15. If c++ refuses to round your number to higher precision change the compiler :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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