-
Notifications
You must be signed in to change notification settings - Fork 0
/
square_root_newton_method.txt
47 lines (40 loc) · 1.62 KB
/
square_root_newton_method.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
/*
Please write a function that accepts a floating number and returns its square-root. You may not use built-in square root function from your language. However, basic operators like addition, subtraction, multiplication are allowed. Please take into consideration the floating precision.
*/
#include <iostream>
#include "math.h"
using namespace std;
int main(){
cout<<"Input an float number: ";
float num;
cin>>num;
if(num<0){
cout<<"wrong input."<<endl;
return -1;
}
else if(num==0){
cout<<"sqrt is 0"<<endl;
return 0;
}
/*We will use Newton's method.*/
float epsilon = 0.0000001;
float x1=10;
while(fabs(x1*x1-num)>epsilon){
x1 = x1-(x1*x1-num)/(2*x1);
}
cout<<"The result is: "<<x1<<endl;
return 0;
}
REMARK:
1. To use abs, you need to #include <cmath>. To use fabs, you need to #include <math.h>
2. We used Newton's method. On the numerical math textbook(author:Burden, Numerical Analysis 9th edition), in the chaptor2(page67, chaptor2 solutions of equations in one variable), he lists
Newton's method works as:Given an equation f(p)=0, we want to get p. Using Taylor series, we have
f(p)= f(x0)+f'(x0)(p-x0)+...
where x0 is the first guess satisfing abs(p-x0)is small.
NOTE: f(p)=0 BECAUSE p IS THE SOLUTION OF THE EQUATION f(p)=0. Then we get:
p = x0 - f(x0)/f'(x0); that is
x1 = x0 - f(x0)/f'(x0) (*)
For our problem, we need to calculate the square root a number. So the equation is x^2=num,i.e.
f(x) = 0 where f(x)=x^2-num;
Then replace f(x) into the equation (*) above, we get
x1 = x0 - (x0^2-num)/(2*x0) = 1/2 * (x0 + num/x0)