public
Created

  • Download Gist
homework_2.5.py
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
# ********** 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)

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.