1

I'm required to determine the n-th(n is a positive 32-bit integer) root of a given floating point number x of arbitrary precision upto 101 significant places. My approach using Newton's method however gives me results upto 53 decimal places only. Any help as such would be appreciated.

#include <bits/stdc++.h>
using namespace std;

double nthRoot(double A, int N)
{
    double xPre = rand() % 10;//INITIAL GUESS
    double eps = 1e-100;//SETTING PRECISION
    double delX = INT_MAX;//SETTING DIFFERENCE BETWEEN VALUES OF 'X'
    double xK;
    while (delX > eps)
        {
            xK = (double)((N - 1.0) * xPre +(double)A/pow(xPre, N-1)) 
                 /(double)N;//FORMULA FROM NEWTON'S METHOD
            delX = abs(xK - xPre);
            xPre = xK;
        }
    return xK;
}

int main()
{
    int N;
    double A;
    cin>>N>>A;
    double nthRootValue = nthRoot(A, N);
    cout.setf(ios::showpoint);
    cout.precision(100);
    cout <<"\n"<< "Nth root is " << nthRootValue << endl;
    return 0;
}
  • 2
    Don't try to do it yourself, use a suitable library (MPFR). – Marc Glisse Dec 24 '17 at 14:03
  • A is already a double, so the cast in `(double)A` is useless. And `double` has only 53 bits of significand (assuming IEEE-754 double precision) so you have no way to get more than that – phuclv Dec 24 '17 at 14:07
  • 1
    I don't think double would be able to support such precision. – leyanpan Dec 24 '17 at 14:08
  • 1
    You can't have 53 decimal places using type `double`. You can't even accurately store number `0.1` using type `double`. – Ron Dec 24 '17 at 14:10
  • I do get them using the precision () manipulator. – Zubair Bashir Dec 24 '17 at 14:13
  • you mean [`std::setprecision`](http://en.cppreference.com/w/cpp/io/manip/setprecision)? it doesn't do what you expected. A type's size is fixed and you can't increase its size and precision – phuclv Dec 24 '17 at 14:16
  • Oh! So how do I get the task done without using a library? Is there a way out? – Zubair Bashir Dec 24 '17 at 14:17
  • "without using a library": why not? If you don't use one, you'll end up basically rewriting one... The point of libraries is to save you the trouble. – Marc Glisse Dec 24 '17 at 18:50

0 Answers0