-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExercise 4.py
More file actions
44 lines (28 loc) · 946 Bytes
/
Copy pathExercise 4.py
File metadata and controls
44 lines (28 loc) · 946 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
40
41
42
43
44
import math
def find_square_root(number):
#Computes square root using math.sqrt()
if number < 0:
return None
return math.sqrt(number)
def find_square_root_newton(number, precision=0.00001):
#Computes square root using Newton-Raphson method.
if number < 0:
return None
if number == 0:
return 0.0
# Initial guess
x = number
while True:
root = 0.5 * (x + number / x)
# Stop when difference is very small
if abs(root - x) < precision:
return root
x = root
# ----------- Testing the functions -----------
test_values = [4, 9, 16, 2, 0, -1]
print("Using math.sqrt():")
for val in test_values:
print(f"Square root of {val} = {find_square_root(val)}")
print("\nUsing Newton-Raphson method:")
for val in test_values:
print(f"Square root of {val} = {find_square_root_newton(val)}")