Square Root using Newton Iteration

Discussion in 'C++' started by StormcasteR, Jan 16, 2009.

  1. StormcasteR

    StormcasteR New Member

    Joined:
    Dec 20, 2008
    Messages:
    4
    Likes Received:
    0
    Trophy Points:
    0
    Occupation:
    Student
    So.Dudes heres the deal.Yesterday a friend of mine wanted me to help him with a function that calculates square root of a positive number using Newton's method.So I came up with this:
    Code:
    #include <iostream>
    #include <cmath>
    using namespace std;
    int main()
    {
      const double tol = 0.000005;
      double value;
      double old_app, new_app;
      cout << "Square root of a number"
           << endl << endl;
      cout << "Enter a positive number: ";
      cin >> value;
      if (value < 0.0)
        cout << "Cannot find square root of negative number"
             << endl;
      else
         if (value == 0.0)
            cout << "square root of "
                 << value
                 << " is 0.00"
                 << endl;
         else
           {
             old_app = value;
             new_app = (old_app + value/old_app)/2;
             while (fabs((new_app-old_app)/new_app) > tol)
               {
                 old_app = new_app;
                 new_app = (old_app + value/old_app)/2;
               }
             cout << "square root of "
                  << value
                  << " is " << new_app
                  << endl;
                  system ("pause");
           }
    }
    
    But I'm really new in C++ and I'm not sure if this is the right way to represent this algorithm?
     
  2. xpi0t0s

    xpi0t0s Mentor

    Joined:
    Aug 6, 2004
    Messages:
    3,009
    Likes Received:
    203
    Trophy Points:
    63
    Occupation:
    Senior Support Engineer
    Location:
    England
    Does it work? Have you entered some test values, and did the correct results come out? If not, what results did you get?
     
  3. StormcasteR

    StormcasteR New Member

    Joined:
    Dec 20, 2008
    Messages:
    4
    Likes Received:
    0
    Trophy Points:
    0
    Occupation:
    Student
    Yes.I entered 78.32for example and the program outputs 8.84986 for square root.Another program I wrote uses heron's formula and the output is the same ( 8.84986) while the normal cmath sqrt() function outputs 8.83176.Anyway, the program works properly but I'm not sure if this is the right way for Newton's method and if the formula I'm using is correct...
     
  4. asadullah.ansari

    asadullah.ansari TechCake

    Joined:
    Jan 9, 2008
    Messages:
    356
    Likes Received:
    14
    Trophy Points:
    0
    Occupation:
    Developer
    Location:
    NOIDA

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice