Writing code to find roots of Quadratic equation was a famous assignment when I was learning GW-BASIC and Borland Turbo C. Recently, I have written following Python code. The output of two sample executions are pasted below as well.
# Quadratic equation with real and non-real roots
# Written by Dr. Tariq Javid as of 31 July 2014
a = raw_input('enter a: ')
b = raw_input('enter b: ')
c = raw_input('enter c: ')
a, b, c = int(a), int(b), int(c)
if ((b ** 2) < (4 * a * c)):
a, b, c = complex(a), complex(b), complex(c)
x1 = ((-b) + ((b ** 2) - 4 * a * c) ** (0.5)) / (2 * a)
x2 = ((-b) - ((b ** 2) - 4 * a * c) ** (0.5)) / (2 * a)
print 'imaginary roots:'
print x1
print x2
else:
a, b, c = float(a), float(b), float(c)
x1 = ((-b) + ((b ** 2) - 4 * a * c) ** (0.5)) / (2 * a)
x2 = ((-b) - ((b ** 2) - 4 * a * c) ** (0.5)) / (2 * a)
print 'real roots:'
print x1
print x2
# Quadratic equation with real and non-real roots
# Written by Dr. Tariq Javid as of 31 July 2014
a = raw_input('enter a: ')
b = raw_input('enter b: ')
c = raw_input('enter c: ')
a, b, c = int(a), int(b), int(c)
if ((b ** 2) < (4 * a * c)):
a, b, c = complex(a), complex(b), complex(c)
x1 = ((-b) + ((b ** 2) - 4 * a * c) ** (0.5)) / (2 * a)
x2 = ((-b) - ((b ** 2) - 4 * a * c) ** (0.5)) / (2 * a)
print 'imaginary roots:'
print x1
print x2
else:
a, b, c = float(a), float(b), float(c)
x1 = ((-b) + ((b ** 2) - 4 * a * c) ** (0.5)) / (2 * a)
x2 = ((-b) - ((b ** 2) - 4 * a * c) ** (0.5)) / (2 * a)
print 'real roots:'
print x1
print x2
No comments:
Post a Comment