Categories
Python

Quadratic Equation Solver

The first program I’m going to attempt is to find real solutions to quadratic equations.

This is my first attempt at a Python program and here is the code:

import math
print('Quadratic Solver - ax\u00B2 + bx + c = 0')
a = float(input('a: '))
b = float(input('b: '))
c = float(input('c: '))
d = math.pow(b,2)-4*a*c
if d>0:
    s1 = (-b+math.sqrt(d))/(2*a)
    s2 = (-b-math.sqrt(d))/(2*a)
    print(s1)
    print(s2)
else:
    print('No real Solutions')

To explain what is going on:

import math
print('Quadratic Solver - ax\u00B2 + bx + c = 0')

The first line is telling it that we want to use some maths functions in this program. Specifically powers and roots.

The second line is nothing more than an instruction to the user what the program is supposed to do and what a, b and c represent.

a = float(input('a: '))

The three lines like this allow the user to input a, b and c. The float bit makes the input a number as opposed to a string.

d = math.pow(b,2)-4*a*c

Next we work out the discriminant to see if there are any real solutions. The math.pow(b,2) means b² is this line.

Finally we have an if: else: statement so if there are any real solutions we find them, and then print them.

s1 = (-b+math.sqrt(d))/(2*a)
s2 = (-b-math.sqrt(d))/(2*a)
print(s1)
print(s2)

The math.sqrt(d) bit is the square root of the discriminant. If there are no real solutions then we say, no real solutions.

How would this work with students?

Now this really is the problem and the question I have not yet answered.

I don’t want to spend time teaching Python, there is not time in the course. But I feel that learning Python will make them better mathematicians and better placed for the future be it university or employment.

How can I ask them to write this program?
What do I need to provide them.

Leave a Reply

Your email address will not be published. Required fields are marked *