Skip to content

Instantly share code, notes, and snippets.

@pdpinch
Created October 6, 2012 15:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pdpinch/3845296 to your computer and use it in GitHub Desktop.
Save pdpinch/3845296 to your computer and use it in GitHub Desktop.
# ********** 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