11
11
12
12
import math
13
13
from decimal import *
14
- getcontext ().prec = 15
15
-
16
- x = Decimal (input ("Enter a number: " ))
17
- z = Decimal (input ("Sqrt guess: " ))
18
-
19
- print ("Math.sqrt(x): \t \t " + str (Decimal (math .sqrt (x )))) # Accurate sqrt
20
-
14
+ getcontext ().prec = 15 # Changing precision of answer, goes to 15 decimal points
15
+
16
+ # Probably an easier way to error-handle this but it works.
17
+ startZ = False # Can't get z without getting x first
18
+ start = False # When user has correctly entered both x and z, start the rest
19
+
20
+ while startZ == False :
21
+ try :
22
+ x = float (input ("Enter a number: " ))
23
+ while x < 1 :
24
+ print ("Please enter a positive number!" )
25
+ x = float (input ())
26
+ startZ = True
27
+
28
+ except ValueError :
29
+ print ("Please only enter number values, try again." )
30
+
31
+ while start == False :
32
+ try :
33
+ z = float (input ("Sqrt guess: " ))
34
+ start = True
35
+ except ValueError :
36
+ print ("Please only enter number values, try again." )
37
+
38
+ # Print answer using built-in math.sqrt function
39
+ # Convert to Decimal for more accuracy, also get the absolute values in case user entered negative num
40
+ # Abs function adapted from https://www.tutorialspoint.com/python/number_abs.htm
41
+ print ("Math.sqrt(x): \t \t " + str (Decimal (math .sqrt (abs (x ))))) # Accurate sqrt
42
+
43
+ # Convert x and z to Decimals
44
+ x = Decimal (abs (x ))
45
+ z = Decimal (abs (z ))
46
+
47
+ # Do the first calculation
21
48
approximate = z - ((z * z - x ) / (2 * z ))
22
- difference = 1
23
- count = 1 # Calculation done once
49
+ difference = 1 # Init the difference in answers at 1 - if init at 0, while loop won't run
50
+ count = 1 # Calculation already done once
24
51
25
52
while difference > 0.00000000001 :
26
- z = approximate
53
+ z = approximate # set new z to be last answer
27
54
approximate = z - ((z * z - x ) / (2 * z ))
28
- difference = z - approximate
55
+ difference = z - approximate # Keep track of difference between z and approx
29
56
count = count + 1
30
57
31
58
print ("Newton's Method: \t " + str (approximate ) + " (" + str (count ) + " iterations)" )
0 commit comments