From bf51f6d3cd10576166fc69286468b2e98d455043 Mon Sep 17 00:00:00 2001 From: Eric Douglas Date: Tue, 20 May 2014 19:49:01 -0300 Subject: [PATCH] 1.1.3 algorithm --- .../UNIT-01/03-problem-solving/lec03.py | 67 +++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 archives/01-introduction-to-computer-science-and-programming/archives/UNIT-01/03-problem-solving/lec03.py diff --git a/archives/01-introduction-to-computer-science-and-programming/archives/UNIT-01/03-problem-solving/lec03.py b/archives/01-introduction-to-computer-science-and-programming/archives/UNIT-01/03-problem-solving/lec03.py new file mode 100644 index 0000000..3e082a0 --- /dev/null +++ b/archives/01-introduction-to-computer-science-and-programming/archives/UNIT-01/03-problem-solving/lec03.py @@ -0,0 +1,67 @@ +""" +# Find the cube root of a perfect cube +x = int(raw_input('Enter an integer: ')) +ans = 0 + +while ans * ans * ans < abs(x): + ans = ans + 1 + # print 'current guess = ', ans + +if ans * ans * ans != abs(x): + print x, ' is not a perfect cube' +else: + if x < 0: + ans = -ans + print 'Cube root of ' + str(x) + ' is ' + str(ans) +""" + +""" +# Find the cube root of a perfect cube +x = int(raw_input('Enter an integer: ')) +for ans in range(0, abs(x) + 1): + if ans**3 == abs(x): + break +if ans**3 != abs(x): + print x, ' is not a perfect cube' +else: + if x < 0: + ans = -ans + print 'Cube root of ' + str(x) + ' is ' + str(ans) +""" + +""" +x = 25000 +epsilon = 0.01 +numGuesses = 0 +ans = 0.0 + +while abs(ans**2 - x) >= epsilon and ans <= x: + ans += 0.00001 + numGuesses += 1 + +print 'numGuesses = ', numGuesses + +if abs(ans**2 - x) >= epsilon: + print 'Failed on square root of ', x +else: + print ans, ' is close to square root of ', x +""" + +x = 12345 +epsilon = 0.01 +numGuesses = 0 +low = 0.0 +high = x +ans = (high + low) / 2.0 + +while abs(ans ** 2 - x) >= epsilon and ans <= x: + #print low, high, ans + numGuesses += 1 + if ans ** 2 < x: + low = ans + else: + high = ans + ans = (high + low) / 2.0 + +print 'numGuesses = ', numGuesses +print ans, ' is close to square root of ', x