Created
September 12, 2014 04:51
-
-
Save pathologicalhandwaving/3c0c1a339a0d1a683293 to your computer and use it in GitHub Desktop.
sqRtAprox.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Kristi Short | |
# Math 180 Numerical Analysis | |
# Fall 2014 | |
# Square Root Approximation | |
# Pythonista Version | |
import math | |
# prompt user for radicand | |
n = float(raw_input("Please enter an integer value for the radicand: ")) | |
toleranceVal = float(raw_input("Please enter a positive integer value for the power of the tolerance: ")) | |
tolerance = math.pow(10, -toleranceVal) | |
print "Note: Computer memory is system dependent, " | |
def findRoot(n, tolerance): | |
itr = 0 | |
with open('SquareRootAprxData', 'w') as f: | |
f.write('#itr,floor, celing, prevMid, mid\n') | |
sqRt = math.sqrt(n) | |
floor = 0 | |
ceiling = n | |
mid = n | |
prevMid = -1 | |
while (math.fabs(mid - prevMid) >= tolerance): | |
f.write('{0},{1},{2},{3}\n'.format(itr,floor,ceiling,prevMid,mid)) | |
prevMid = mid | |
mid = float((floor+ceiling)/2) | |
if mid**2 > n: | |
ceiling = mid | |
else: | |
floor = mid | |
itr = itr + 1 | |
return mid | |
root = findRoot(n, tolerance) | |
print "The approximated root of " + str(n) + " is " + str(root) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment