Write Your Own Square Root Function
Ever wondered how your calculator calculates the square root for a given number? It probably uses power series but an easier to grasp approach is the following:
Take a number t Let r be your guess of what the square root might be After that repeat the following a few times: r = (r+t/r)/2.0 r will now be a number pretty close to the square root of t
Below are two version of what this would look like in Python and C++. The initial guess is half the number t.
In Python:
def sqrt(t):
r = t/2.0; t = float(t)
i = 0
while i < 10:
r = (r+t/r)/2.0
i += 1
return r
In C++
long double sqrt(long double t) {
long double r = t/2;
for ( int i = 0; i < 10; i++ ) {
r = (r+t/r)/2;
}
return r;
}
April 12th, 2007 at 10:45 pm
I have one work but i can’t write root square if can you help me