-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathroots.py
More file actions
39 lines (28 loc) · 743 Bytes
/
Copy pathroots.py
File metadata and controls
39 lines (28 loc) · 743 Bytes
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
import sys
__author__ = 'johanvergeer'
def sqrt(x):
"""Compute square roots using the method of Heron of Alexandria.
Args:
x: The number for which the square root is to be computed.
Returns:
The square root of x.
"""
if x < 0:
raise ValueError(
"Cannot compute square root of negative number {}".format(x))
guess = x
i = 0
while guess * guess != x and i < 20:
guess = (guess + x / guess) / 2.0
i += 1
return guess
def main():
try:
print(sqrt(9))
print(sqrt(2))
print(sqrt(-1))
print("This is never printed")
except ValueError as e:
print(e, file=sys.stderr)
if __name__ == '__main__':
main()