-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathsqrttest.py
61 lines (48 loc) · 1.05 KB
/
sqrttest.py
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#!/usr/bin/env python
#
# Author Dario Clavijo 2015
# GPLv3
# implementation acording to whikipedia: https://es.wikipedia.org/wiki/C%C3%A1lculo_de_la_ra%C3%ADz_cuadrada
def sqrt(x):
r = x
t = 0
while t != r:
t = r
r = 0.5 * (x / r + r)
return r
def sqrt(n):
x = n
y = 1
e = 0.00000001
while (x - y) > e:
x = (x + y) / 2
y = n / x
return x
# given the x**2-2=0 condition we bruteforce an aproximation to sqrt(2)
def sqrttest():
target = 2.0
x = 2.0
error = 1
step = 0.5
lower_error = 1
i = 0
c = 0
last_aprox = None
while error != 0:
i = i + 1
error = (x**target) - target
x = x - (error * step)
if error < lower_error:
lower_error = abs(error)
print(
(
"Count: %d, Aprox: %s, Error: %s, LowerError: %s"
% (
i,
x,
error,
lower_error,
)
)
)
sqrttest()