c++floating-pointprecisionsqrt

I implemented my own square root function in c++ to get precision upto 9 points but it's not working


I want to get square root of a number upto 9 precision points so I did something like below but I am not getting correct precision. Here e is the precision which is greater than 10^9 then also ans is upto 5 precision points. What am I doing wrong here??

    #include <iostream>
    using namespace std;
    long double squareRoot(long double n) 
        { 

            long double x = n; 
            long double y = 1; 
            long double e = 0.00000000000001; 
            while (x - y > e) 
            { 
                x = (x + y) / 2; 
                y = n / x; 
            } 
            cout << x << "\n";
            return x; 
        } 

    int main() 
    {
        int arr[] = {2,3,4,5,6};
        int size = sizeof(arr)/sizeof(arr[0]);
        long double ans = 0.0;
        for(int i=0; i<size; i++)
        {
            ans += squareRoot(arr[i]);
        }

        cout << ans << "\n";
        return 0;
    }

The output is

1.41421
1.73205
2
2.23607
2.44949
9.83182

What should I do to get precision upto 9 points??


Solution

  • There are two places at which precision plays a role:

    You can only get output in desired precision if both value and stream are precise enough.

    In your case, the calculated value doesn't seem to be a problem, however, default stream precision is only five digits, i. e. no matter how precise your double value actually is, the stream will stop after five digits, rounding the last one appropriately. So you'll need to increase stream precision up to the desired nine digits:

    std::cout << std::setprecision(9);
    // or alternatively:
    std::cout.precision(9);
    

    Precision is kept until a new one is set, in contrast to e. g. std::setw, which only applies for next value.