描述
Professor Chambouliard has just completed an experiment on gravitational waves. He measures their effects on small magnetic particles. This effect is very small and negative. In his first experiment the effect satisfies the equation:
x**2 + 1e9 * x + 1 = 0.
Professor C. knows how to solve equations of the form:
g(x) = a x ** 2 + b x + c = 0 (1)
using the “discriminant”.
It finds that the roots of x**2 + 1e9 * x + 1 = 0 are x1 = -1e9 and x2 = 0. The value of x1 - good or bad - does not interest him because its absolute value is too big.
On the other hand, he sees immediately that the value of x2 is not suitable!
He asks our help to solve equations of type (1) with a, b, c strictly positive numbers, and b being large (b >= 10 ** 9).
Professor C. will check your result x2 (the smaller root in absolute value. Don’t return the other root!) by reporting x2 in (1) and seeing if abs(g(x2)) < 1e-12.
Task:
solve(a, b, c)
that will return the “solution” x2 of (1) such as abs(a * x2 ** 2 + b * x2 + c) < 1e-12.
Example:
for equation 7*x**2 + 0.40E+14 * x + 8 = 0 we can find: x2 = -2e-13 which verifies abs(g(x)) < 1e-12.
分析
这不是一道好的编程题目,只是在考一个人是否知道数学中的"Catastrophic cancellation"。
对于一元二次多项式:a
x
2
x^2
x2 + bx + c = 0
一般解是:
−
b
±
b
2
−
4
a
c
2
a
\frac{-b\pm\sqrt{b^2-4ac}}{2a}
2a−b±b2−4ac
但对于
b
2
b^2
b2远大于ac的情况,其中一个根要用:
2
c
−
b
−
b
2
−
4
a
c
\frac{2c}{-b-\sqrt{b^2-4ac}}
−b−b2−4ac2c来求解。(另一个根是
−
b
−
b
2
−
4
a
c
2
a
\frac{-b-\sqrt{b^2-4ac}}{2a}
2a−b−b2−4ac)
参考文档:关于Cancellation
实现
import "math"
func Quadratic(a float64, b float64, c float64) float64 {
d:= b * b - 4 * a * c
return 2 * c / (-b - math.Sqrt(d))
}