Hi friends,
I have written the following program to display a specific o/p:

``````def square_root(a):
if a>1.0:
x=a-1.0
elif a==1.0:
return 1.0
else:
pass
while True:
y=(x+a/x)/2
if math.fabs(y-x)<0.0000001:
break
x=y
return x

import math
i=1.0
while i<=9.0:
print i,
sqrt=square_root(i)
print sqrt,
math_sqrt=math.sqrt(i)
print math_sqrt,
print ''*4,
difference=math_sqrt-sqrt
print math.fabs(difference)
i=i+1``````

The output is to display four columns:
First is 'a' , Second is square root of 'a' by the `square_root(a)` function I have written , Third is the square root of 'a' my math.sqrt function (inbuilt), the fourth column is to display the absolute value of the difference between column 2 and 3.

The first 3 columns display fine except for the last column. Instead of displaying the difference between the 2 columns, it {strangely} adds up the second and the third columns and finds the absolute.
What is the problem? Kindly help.

Thank You.

I think it behaves perfectly fine, here is my output:

``````1.0 1.0 1.0  0.0
2.0 1.41421356237 1.41421356237  1.59472435257e-012
3.0 1.73205081001 1.73205080757  2.44585018905e-009
4.0 2.00000000003 2.0  2.62145860574e-011
5.0 2.23606798501 2.2360679775  7.51019246792e-009
6.0 2.44948974278 2.44948974278  6.2172489379e-015
7.0 2.64575131106 2.64575131106  3.66817687336e-013
8.0 2.82842712475 2.82842712475  6.9610983644e-012
9.0 3.00000000007 3.0  6.61648513756e-011``````

Also remember that most computer languages represent a floating point number in such a way that there is the possibility of a tiny last-digit error.

To get a better output of your results you should do some formatting:

``````def square_root(a):
if a > 1.0:
x = a - 1.0
elif a == 1.0:
return 1.0
else:
pass
while True:
y = (x + a/x)/2
if math.fabs(y-x) < 0.0000001:
break
x = y
return x

import math
i = 1.0
while i <= 9.0:
sqrt = square_root(i)
math_sqrt = math.sqrt(i)
difference = math.fabs(math_sqrt - sqrt)
print "%0.1f %0.9f %0.9f %0.9f" % (i, sqrt, math_sqrt, difference)
i = i + 1

"""
my output --->
1.0 1.000000000 1.000000000 0.000000000
2.0 1.414213562 1.414213562 0.000000000
3.0 1.732050810 1.732050808 0.000000002
4.0 2.000000000 2.000000000 0.000000000
5.0 2.236067985 2.236067977 0.000000008
6.0 2.449489743 2.449489743 0.000000000
7.0 2.645751311 2.645751311 0.000000000
8.0 2.828427125 2.828427125 0.000000000
9.0 3.000000000 3.000000000 0.000000000
"""``````

Hi,