Created
October 6, 2012 15:54
-
-
Save pdpinch/3845296 to your computer and use it in GitHub Desktop.
partial solution to exercise 2.5 of http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-189-a-gentle-introduction-to-programming-using-python-january-iap-2011/assignments/MIT6_189IAP11_hw2.pdf
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
# ********** Exercise 2.5 ********** | |
# code for roots function | |
# given the coefficients for a quadratic equation | |
# returns the two roots | |
# if the roots are complex, exit | |
def find_roots(a,b,c): | |
# give up if the roots are complex | |
assert not roots_are_complex(a,b,c) | |
d = math.sqrt(b**2 - 4*a*c) | |
root1 = (-1*b + d)/2*a | |
root2 = (-1*b - d)/2*a | |
return root1, root2 | |
# given the coefficients for a quadratic equation | |
# returns true if the roots are complex | |
# THIS DOESN'T ACTUALLY WORK | |
def roots_are_complex(a,b,c): | |
return False | |
# Test Cases | |
print "roots of x^2 + 2x + 1 are ", find_roots(1,2,1) | |
print "roots of x^2 + 4x + 1 are ", find_roots(1,4,1) | |
print "roots of x^2 + 4x are ", find_roots(1,4,0) | |
print "roots of 16x^2 + 4x + 16", find_roots(16,4,16) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment