### Thread: square root precision

1. No Profile Picture
Registered User
Devshed Newbie (0 - 499 posts)

Join Date
Aug 2004
Posts
18
Rep Power
0

#### square root precision

I saw a C++ program the other day that asked for a number and found the square root to as many decimal places as you told it. I couldn't get it to compile, but since I am learning python I thought I would try to write it in python..

It also timed how long it took to calculate the number. So I want to make a python program that does this:

Number? 3
Precision? 5

Answer: 1.16282
Time: 3 seconds

obviously made up those numbers and it for sure wouldn't take 3 seconds to find the square root of three to 5 decimal places. :P

So anyone want to tell me how to set the precision and create a timer? Thanks!!
2. No Profile Picture
Registered User
Devshed Newbie (0 - 499 posts)

Join Date
Jul 2004
Posts
10
Rep Power
0
Code:
```A = 8.251 # sqrt(A)
P = 45    # precition

e = long(10**P)
a = long(A*e)
x = a
for _ in range(20):
x_ = (x+a*e/x)/2
if x_ == x:
print x # x/e
break
else:
x = x_

#
# test
#
import math
print math.sqrt(A)```
3. No Profile Picture
Registered User
Devshed Newbie (0 - 499 posts)

Join Date
Jul 2004
Posts
10
Rep Power
0
Code:
```import time

cur = time.time()

# do something...
for _ in xrange(1000000): a = 12.565/12312.2313 # for example

print 'time:', time.time()-cur, 'sec'```
4. No Profile Picture
Registered User
Devshed Newbie (0 - 499 posts)

Join Date
Jul 2004
Posts
10
Rep Power
0
I've mistaken!
Don't use FOR _ IN RANGE!!!

Try better:
Code:
```
A = 200 # sqrt(A)
P = 80    # precition

e = long(10**P)
a = long(A*e)
x = a
while True:
x_ = (x+a*e/x)/2
if x_ == x:
print x # x/e
break
else:
x = x_

#
# test
#
import math
print math.sqrt(A)```
5. No Profile Picture
Contributing User
Devshed Newbie (0 - 499 posts)

Join Date
Dec 2001
Location
Houston, TX
Posts
383
Rep Power
13
FYI: you shouldn't expect any decent precision with floating point math in Python
6. No Profile Picture
......@.........
Devshed Beginner (1000 - 1499 posts)

Join Date
Jun 2004
Posts
1,345
Rep Power
56
C++ and C extended precision libraries are available and you can have python call them. It requires work on your part.

You are better off just getting the GMP (gnu multiple precison) library from
ftp.gnu.org and using it with your C or C++ compiler.
7. No Profile Picture
Registered User
Devshed Newbie (0 - 499 posts)

Join Date
Aug 2004
Posts
18
Rep Power
0
Thanks for the replies guys.