Answer to Question #29183 in C++ for amira kausar

Question #29183
Approximating the square root

Implement the sqrt function. The square root of a number, num, can be approximated by repeatedly performing a calculation using the following formula :

nextGuess = (lastGuess + (num / numGuess)) /2

The initial guess can be any positive value (e.g., 1). This value will be the starting vale for lastGuess. If the difference between nextGuess and lastGuess is less than a very small number, such as 0.0001, you can claim that nextGuess is the approximated square root of num. If not, nextGuess becomes the lastGuess and the approximation process continues.
1
Expert's answer
2013-04-29T09:01:04-0400
// Square root.cpp : Defines the entry point for the console application.

#include "math.h"
#include "iostream"
using namespace std;
int main()
{
double lastGuess = 1;
double prevGuess = 0;
double eps = 0.000001;
int numGuess = 1;
double num;
cout << "Enter number for evaluation: ";
cin >> num;

while(abs(lastGuess - prevGuess) > eps)
{
double newGuess = (lastGuess + (num / numGuess)) / 2;
prevGuess = lastGuess;
lastGuess = newGuess;
numGuess++;
}
cout << prevGuess * 1000 << endl; // please make sure that multiplying by 1000 is necessary
& // because it wasn't in your algorithm.
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS