Advertisement
Guest User

Untitled

a guest
Mar 27th, 2017
39
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.79 KB | None | 0 0
  1. #include <iostream>
  2. using namespace std;
  3. /*
  4. Code snippet to find the approximate square root of a number using Newton-Raphson Method.
  5. let x be the square root, => x = √input
  6. => x^2 - input = 0
  7. =>By NR Method , we have x-[(x^2-input)/2x]
  8. */
  9. int main()
  10. {
  11. float inNumber;
  12. float threshold = 0.01f; //minimum error tolerance threshold for the square root
  13. cout << "Enter a number to find its square root : " << endl;
  14. cin >> inNumber;
  15. if(inNumber < 0) inNumber *= -1;//handle negative inputs
  16. float sqrtGuess = inNumber/2;
  17. while(sqrtGuess*sqrtGuess - inNumber >= threshold)
  18. {
  19. sqrtGuess = sqrtGuess - (((sqrtGuess*sqrtGuess)-inNumber)/(2*sqrtGuess));
  20. }
  21. cout << "The square root of "<< inNumber << " is approximately : "<<sqrtGuess<<endl;
  22. return 0;
  23. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement