Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- using namespace std;
- /*
- Code snippet to find the approximate square root of a number using Newton-Raphson Method.
- let x be the square root, => x = √input
- => x^2 - input = 0
- =>By NR Method , we have x-[(x^2-input)/2x]
- */
- int main()
- {
- float inNumber;
- float threshold = 0.01f; //minimum error tolerance threshold for the square root
- cout << "Enter a number to find its square root : " << endl;
- cin >> inNumber;
- if(inNumber < 0) inNumber *= -1;//handle negative inputs
- float sqrtGuess = inNumber/2;
- while(sqrtGuess*sqrtGuess - inNumber >= threshold)
- {
- sqrtGuess = sqrtGuess - (((sqrtGuess*sqrtGuess)-inNumber)/(2*sqrtGuess));
- }
- cout << "The square root of "<< inNumber << " is approximately : "<<sqrtGuess<<endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement