August 26th, 2004, 08:25 PM

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!!
August 27th, 2004, 01:27 AM

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)
August 27th, 2004, 01:30 AM

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'
August 27th, 2004, 01:39 AM

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)
August 27th, 2004, 01:29 PM

FYI: you shouldn't expect any decent precision with floating point math in Python
August 27th, 2004, 03:06 PM

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.
August 27th, 2004, 03:22 PM

Thanks for the replies guys.