Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit e8f19c6

Browse files
Lot of error handling (absolute values etc), some comments
1 parent b26ec97 commit e8f19c6

File tree

1 file changed

+38
-11
lines changed

1 file changed

+38
-11
lines changed

‎09-NewtonSquareRoots.py

Lines changed: 38 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -11,21 +11,48 @@
1111

1212
import math
1313
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
2148
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
2451

2552
while difference > 0.00000000001:
26-
z = approximate
53+
z = approximate# set new z to be last answer
2754
approximate = z - ((z*z - x) / (2 * z))
28-
difference = z - approximate
55+
difference = z - approximate# Keep track of difference between z and approx
2956
count = count + 1
3057

3158
print("Newton's Method: \t" + str(approximate) + " (" + str(count) + " iterations)")

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /