-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathroots6.py
More file actions
38 lines (28 loc) · 797 Bytes
/
roots6.py
File metadata and controls
38 lines (28 loc) · 797 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
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.
Raises:
ValueError: If x is negative.
'''
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)
print("Program execution continues normally here.")
if __name__ == '__main__':
main()