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.
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.
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.
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.
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.
|
|