Skip to content

Instantly share code, notes, and snippets.

@whs
Forked from anonymous/chal.py
Last active December 19, 2015 04:18
Show Gist options
  • Save whs/5896103 to your computer and use it in GitHub Desktop.
Save whs/5896103 to your computer and use it in GitHub Desktop.
from __future__ import division
import math
def s(a,b,c,e=1):
try:
p2 = math.sqrt(b**2 - (4*a*c))
return ((-1*b)+p2)/(a*2) if e>0 else ((-1*b)-p2)/(a*2)
except ValueError:
return None
def smaller_root(a,b,c):
s1=s(a,b,c)
s2=s(a,b,c,-1)
return min(s1,s2)
if __name__ == "__main__":
o=smaller_root(1,2,1)
if o:
print o
else:
print "Error: No real solutions"

Challenge: Given numbers a, b, and c, the quadratic equation ax2+bx+c=0 can have zero, one or two real solutions (i.e; values for x that satisfy the equation). The quadratic formula

x=−b±b2−4ac√2a

can be used to compute these solutions. The expression b2−4ac is the discriminant associated with the equation. If the discriminant is positive, the equation has two solutions. If the discriminant is zero, the equation has one solution. Finally, if the discriminant is negative, the equation has no solutions.

Write a Python function smaller_root that takes an input the numbers a , b and c and returns the smaller solution to this equation if one exists. If the equation has no real solution, print the message "Error: No real solutions" and simply return. Note that, in this case, the function will actually return the special Python value None .

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment