A more accurate quadratic solution
These examples show the effects of rounding errors in the simple quadratic equation sloving spreadsheet from 13A and a slighty improved version that is more accurate.
Links
Download spreadsheet with errors (.xlsx) Download improved spreadsheet (.xlsx) Download Python code with error Download improved Python codeSimple quadratic solution with rounding errors – spreadsheet
Improved quadratic solution with rounding errors – spreadsheet
Simple quadratic equation solution with rounding errors – Python
import math
# Enter the coefficients of the
# quadratic equation ax^2+bx+c
# below
a = 1/10000
b = -999999999/100000000
c = -1/1000
# Simple solution
d = b*b-4*a*c
print ( "Discriminant = ",d)
if d < 0:
print ("No real solution")
exit()
x1 = (-b-math.sqrt(d))/(2*a)
x2 = (-b+math.sqrt(d))/(2*a)
print("x = ",x1," or ",x2)
# Output:
#
# Discriminant = 100.00000019999999
# x = -9.99999993922529e-05 or 100000.0
Improved quadratic equation solution – Python
import math
# Enter the coefficients of the
# quadratic equation ax^2+bx+c
# below
a = 1/10000
b = -999999999/100000000
c = -1/1000
# Solution that reduces rounding errors
d = b*b-4*a*c
print ( "Discriminant = ",d)
if d < 0:
print ("No real solution")
exit()
if b < 0:
q = -0.5 * (b-math.sqrt(d))
else:
q = -0.5 * (b+math.sqrt(d))
x1 = q/a
x2 = c/q
print("x = ",x1," or ",x2)
# Output:
#
# Discriminant = 100.00000019999999
# x = 100000.0 or -0.0001
The simple spreadsheets and python examples on this page may be copied freely.