Python 3 NOTE: This is an example of a function that DOES something (it puts the
ID: 3778524 • Letter: P
Question
Python 3 NOTE: This is an example of a function that DOES something (it puts the value(s) of the root(s) in a list), and it RETURNS something (the number of roots)
Sample exercise 4.1
When the discriminant == 0 r1 and r2 are the same
so we only report one. You've unnecessarily done the
calculation twice.
"""
#Algebra: Solve Quadratic Equations
a, b ,c = eval(input("Enter the values for a, b, c:"))
disc= (b*b) - (4 * a * c)
if disc>0:
r1= (-b + (b*b - 4 * a * c)**0.5) / (2*a)
r2= (-b - (b*b - 4 * a * c)**0.5) / (2*a)
print ("Display two roots",r1, r2)
elif disc==0:
r1= (-b + (b*b - 4 * a * c)**0.5) / (2*a)
r2= (-b - (b*b - 4 * a * c)**0.5) / (2*a)
print ("Display one root", r1)
else:
print ("The equation has no real roots")
Explanation / Answer
def solveQuadratic(eqn, roots):
a = float(eqn[0])
b = float(eqn[1])
c = float(eqn[2])
disc = (b ** 2)- (4 * a * c)
if disc > 0:
roots.append(-b + (disc ** 0.5) / (2 * a))
roots.append(-b -(disc ** 0.5) / (2 * a))
return 2
elif disc == 0:
roots.append(-b / (2 * a))
return 1
else:
return 0
def main():
#taking equation as ax^2 + bx + c
a,b,c = eval(input("Please give a, b, c of the quadratic equation: "))
eqn = []
eqn.append(a)
eqn.append(b)
eqn.append(c)
roots = []
no_of_roots = solveQuadratic(eqn, roots)
print("Number of roots = "+ str(no_of_roots))
for i in range (0,no_of_roots):
print("root" + str(i+1) + " : " + str(roots[i]))
main()
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.