解の公式をそのまま数値計算に適用することで起こる破綻
数値計算のためのトリックのいい例あんも.icon
$ x^2 -(100000.00001)x + 1 = 0 を解く
code:jl
function getroot2(a, b, c)
D = b^2 - 4a*c
root1 = (-b + sqrt(D)) / (2a)
root2 = (-b - sqrt(D)) / (2a)
return root1, root2
end
getroot2(1, -100000.00001, 1) # (100000.0, 1.0000003385357559e-5)
因数分解による方法
$ (x - 10^5)(x - 10^{-5}) = 0
避けた表現にすればよい
ちょっとしたトリックで回避できる
有理化による同値変形
解と係数の関係
code:jl
function getroot2(a, b, c)
D = b^2 - 4a*c
if b > 0
root1 = (-b - sqrt(D)) / (2a)
root2 = (2c) / (-b - sqrt(D)) # 解と係数の関係を用いて c / (a * root1) でもよい
else
root1 = (-b + sqrt(D)) / (2a)
root2 = (2c) / (-b + sqrt(D))
end
return root1, root2
end
getroot2(1, -100000.00001, 1) # (100000.0, 1.0e-5)