Go语言实现Floating-point Approximation (III)

描述

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} 2ab±b24ac
但对于 b 2 b^2 b2远大于ac的情况,其中一个根要用: 2 c − b − b 2 − 4 a c \frac{2c}{-b-\sqrt{b^2-4ac}} bb24ac 2c来求解。(另一个根是 − b − b 2 − 4 a c 2 a \frac{-b-\sqrt{b^2-4ac}}{2a} 2abb24ac
参考文档:关于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)) 
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值