In: Computer Science
Newtons method for approximating square roots.
The next iteration is the average of the previous iteration and the ratio of the number in question to the previous iteration.x_i = ( x_(i-1) + number/x_(i-1) ) / 2
if i is 0 the approximation is half the number.
Pre: number & interations are non-negative integers
Post: return an approximation of sqrt(number) , the return value is double
double newton(size_t number, size_t iterations){}
In this program, we have to approximate square root of a number using newtons method.
Initially set squareRoot = 0.5*number
then create a loop that repeats iterations times. Inside the loop set sqaureRoot = (squareRoot + (double)number/squareRoot)/2
After the loop terminates, return squareRoot
function:
double newton(size_t number, size_t iterations){
double squareRoot = (double)number/2;
for(int i = 1; i <= iterations; i++)
squareRoot = (squareRoot + (double)number/squareRoot)/2;
return squareRoot;
}
sample program to test this function:
#include <stdio.h>
#include <math.h>
double newton(size_t number, size_t iterations){
double squareRoot = (double)number/2;
for(int i = 1; i <= iterations; i++)
squareRoot = (squareRoot + (double)number/squareRoot)/2;
return squareRoot;
}
int main(){
double number; int iterations;
printf("Enter a number: ");
scanf("%lf", &number);
printf("Number of iterations: ");
scanf("%d",&iterations);
printf("\n\n Real square root: %lf\n",sqrt(number));
printf("Approximated square root:
%lf\n",newton(number,iterations));
}
sample inputs and outputs: