how to make a c++ program (i'm using turbo c++) that would find the square root of a certain number by using newton's approximation method.
How to make a c++ program (i'm using turbo c++) that would find the square root of a certain number?
Do you understand Newton's approximation method for finding a square root?
Given a function f(x) where the solution of f(x)=0 has an initial approximation x*, you get a new (usually better) approximation by calculating:
x* - f(x*)/f'(x*)
where f'(x) is the derivative.
So you need a function where the solution of f(x)=0 is the square root of your number K. One such function is
f(x) = x^2 - K.
So your program should take an initial guess at the solution. You can use K itself as a guess. The method converges pretty quickly, so K is good enough.
Then you let variable x = your initial guess.
Keep repeating x = x - f(x)/f'(x) until you're satisfied.
Print out the final value of x.
There are a number of ways of being "satisfied".
One is testing the value of x to see how good an answer it is, e.g., testing if fabs(x^2 - k) %26lt; tolerance. Another is testing if the difference between the previous and current values of x is less than a tolerance.
Your C++ code will need to:
read in a number
set x to the initial guess
loop calculating the new value of x
until the termination condition is satisfied
print the final value of x
Reply:Shouldn't you be doing your own homework?
Reply:#include %26lt;math.h%26gt;
#define TOLERANCE 0.00000004
const double mysqrt(const double number) {
double guess = number;
while (fabs(guess * guess - number) %26gt;= TOLERANCE) {
guess -= (guess * guess - number) / (2 * guess);
}
return guess;
}
Reply:#include%26lt;iostream.h%26gt;
#include%26lt;conio.h%26gt;
#include%26lt;math.h%26gt;
void main()
{
double num,result;
cout%26lt;%26lt;"Enter The Number U Want to Found Square Root";
cin%26gt;%26gt;num;
result = sqrt(num);
cout%26lt;%26lt;"Square Root of"%26lt;%26lt;num%26lt;%26lt;"is:"%26lt;%26lt;result;
}
Reply:#include %26lt;iostream.h%26gt;
#include %26lt;math.h%26gt;
int main ()
{
double num, result;
num = 1024.0;
result = sqrt (num);
cout%26lt;%26lt;result;
return 0;
}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment