scientific-programming-exer.../ex_07.py

75 lines
1.6 KiB
Python
Raw Normal View History

2018-10-31 12:48:36 +00:00
#!/usr/bin/python3
from math import sqrt
from util.io import readvalue
def solution_count(a, b, c):
"""
Calculates the number of real solutions
for a*x**2 + b*x + c = 0.
Returns: 0 or 1 or 2
Method:
After doing some fiddling you can get the equation
(x + b/(2*a))**2 = (b/(2*a))**2 - c/a
You can derive that the equation has
no real solution, if (b/(2*a))**2 - c/a < 0
one real solution, if (b/(2*a))**2 - c/a = 0,
two real solutions, if (b/(2*a))**2 - c/a > 0.
"""
rterm = (b/(2*a))**2 - c/a
if(rterm < 0):
return 0
if(rterm == 0):
return 1
if(rterm > 0):
return 2
def solutions(a, b, c):
"""
Returns the solution(s) of a*x**2 + b*x + c = 0.
If the equation has no solution, it returns None,
a tuple of the soltions, otherwise.
"""
# Get the number of solutions:
number_of_solutions = solution_count(a, b, c)
if(not number_of_solutions):
return
if(number_of_solutions == 1):
return (-b / (2*a), )
else:
rterm = sqrt((b/(2*a))**2 - c/a)
return (-b / (2*a) + rterm, -b / (2*a) - rterm)
if( __name__ == "__main__"):
print("Program to find the solution(s) for a*x**2 + b*x + c = 0")
a = readvalue("a > ", float)
b = readvalue("b > ", float)
c = readvalue("c > ", float)
number_of_solutions = solution_count(a, b, c)
messages = ["There are no real solutions."
, "There is exactly one real solution."
, "There are exactly two real solutions."]
print(messages[number_of_solutions])
if(number_of_solutions == 1):
print("The solution is:", solutions(a, b, c)[0])
if(number_of_solutions == 2):
print("The first solution is:", solutions(a, b, c)[0])
print("The second solution is:", solutions(a, b, c)[1])