Exercise 100

Create an algorithm in Python as a function that gives the solution of a quadratic equation ax ^ 2 + bx + c = 0.

Solution


from math import sqrt
# a quadratic equation ax^2 + bx + c = 0 can be represented by the tuple (a , b , c)
def solveEquation(a , b, c):
delta = b*b -4*a*c

# if delta > 0 , then the equation admits two distinct solutions
if delta>0 :
delta_sr= sqrt(delta)
x1 =(- b + delta_sr)/2*a
x2 =(- b - delta_sr)/2*a
return ("The set of solutions is : " , set({x1,x2}))

# else if delta == 0 , the equation admits a double solution
elif delta == 0:
x_double = -b/(2*a)
return ("Solution double : " , x_double)

# if not the equation does not admit a solution
else:
return("No solution for this equation !")

# First example x^2 + 5x - 6 = 0
print("First example : " , solveEquation(1 , 5 , 6))

# Second example x^2 - 3x + 5 = 0
print("Second example : " , solveEquation(1 , -3 , 5))

# 3rd example : 4x^2 - 4x + 1
print("3rd example : " , solveEquation(4 , -4 , 1))

The output is:
First example :  ('The set of solutions is : ', {-3.0, -2.0})
Second example :  No solution for this equation !
3rd  example :  ('Solution double : ', 0.5)

Younes Derfoufi
my-courses.net

Leave a Reply