PYTHON Program: To solve a quadratic equation (GCSE Level) A quadratic equation has the form: ax2 + bx + c = 0 It is solved by using the formula: To set up a program to solve the equation we need to ask the user for input. What needs to be done?First we must get the user to rearrange their equation into the form ax2 + bx + c = 0, then they need to input their values for a, b and c. So first of all we need to write instructions for the user, and to ask for that input. But we have to remember that all input is taken to be a string value! We therefore have to convert the user input into a number before we can use those inputs in the formula.
We then need to get the computer to apply the equation to their value and finally we need the computer to output the values to the screen. For the values to be 'user friendly' we have to consider 'rounding' the answer. In the equation there is a square root function. To call upon this function in Python3 we will need to call on a library of maths functions. We must therefore head the program with:
We can then use the math.sqrt(x) function within our program.
Writing the programIt is always a good idea to give the program a title and/or to say what it is going to do. Just jumping in with asking for input is seldom user-friendly.
Now we have to translate the equation into python code for the computer. The solution will give us the value of 'x'. There will be two values for 'x' - one will be obtained when we us the '+' value after the -b and the other when we use a '-' value. We therefore have to have two x variable values. Let's call them x1 and x2.
Now - if (b2-4ac) is a negative value we have a problem! The square root of a negative number is an imaginary number - something you do at A level - not GCSE. We therefore have to stop the program at this point and tell the user there is a problem if they enter values for a, b and c that will result in an imaginary number in the solution. We can therefore put a 'test' in - before we get to the sqrt() function - and stop the computer attempting to do this calculation. To do this we can use the 'If - Else' coding.
Visual embellishmentsIt is always a good idea to took at the output from your program.
Now take a look at my program.... |
|