import numpy as np
$ax^2 + bx + c = 0$
$x_{1,2} = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a}$
a = np.float32(1.)
b = np.float32(-1000.001)
c = np.float32(1.)
x1 = (-b + np.sqrt(b * b - 4 * a * c, dtype=np.float32)) / (2 * a)
x2 = (-b - np.sqrt(b * b - 4 * a * c, dtype=np.float32)) / (2 * a)
print(x1, x2)
1000.0 0.001007080078125
print(a * x1 * x1 + b * x1 + c)
print(a * x2 * x2 + b * x2 + c)
0.0234375 -0.007080047391355038
$x_1 + x_2 = - \frac{b}{a}$
$x_1x_2 = \frac{c}{a}$
x1 = (-b + np.sqrt(b * b - 4 * a * c, dtype=np.float32)) / (2 * a)
print(x1)
x2 = c / x1 / a
x1 = -b/a - x2
print(x1, x2)
print(a * x1 * x1 + b * x1 + c)
print(a * x2 * x2 + b * x2 + c)
1000.0 999.9999765625 0.001 2.3399479687213898e-08 2.3437500051848303e-08
Let us write a little expressions for our roots
$$ \frac{1000.001 \pm \sqrt{1000.001^2 - 4}}{2} = \frac{1000.001 \pm 999.999}{2} = 1000 \text{ and } 0.00099999999$$But if we have only 5 significant digits we have to truncate out exact answer to the form
$$ \frac{1000.001 \pm 999.999}{2} \approx \frac{1000.00 \pm 999.99}{2} = 999.95 \text{ and } 0.005$$BUT!
$$ \frac{1}{999.95} = 0.00100005 $$is much more accurate root!
N = 1000000
items = np.array([1. / n**2 for n in range(1, N+1)], dtype=np.float32)
print(items.sum(), np.pi**2 / 6.)
print(np.abs(items.sum() - np.pi**2 / 6.))
1.6449317 1.6449340668482264 2.392844625331847e-06
val1 = np.float32(0.0)
for i in range(items.shape[0]):
val1 += items[i]
print(val1, np.abs(val1 - np.pi**2 / 6.))
val2 = np.float32(0.0)
for i in range(items.shape[0]-1, -1, -1):
val2 += items[i]
print(val2, np.abs(val2 - np.pi**2 / 6.))
1.6447253 0.0002087441248377342 1.644933 1.0815424402732532e-06