所有,
我刚刚开始玩朱莉娅语,我很享受它.在第3个教程结束时,有一个有趣的问题:对二次公式进行泛化,使其解决任何n阶多项式方程的根.
这让我感到震惊,因为(a)一个有趣的编程问题和(b)一个有趣的Julia问题.谁有人解决了这个?作为参考,这里是带有几个玩具示例的Julia代码.同样,这个想法是为任何n阶多项式制作这个通用的.
干杯,
亚伦
function derivative(f)
return function(x)
# pick a small value for h
h = x == 0 ? sqrt(eps(Float64)) : sqrt(eps(Float64)) * x
# floating point arithmetic gymnastics
xph = x + h
dx = xph - x
# evaluate f at x + h
f1 = f(xph)
# evaluate f at x
f0 = f(x)
# divide the difference by h
return (f1 - f0) / dx
end
end
function quadratic(f)
f1 = derivative(f)
c = f(0.0)
b = f1(0.0)
a = f(1.0) - b - c
return (-b + sqrt(b^2 - 4a*c + 0im))/2a, (-b - sqrt(b^2 - 4a*c + 0im))/2a
end
quadratic((x) -> x^2 - x - 2)
quadratic((x) -> x^2 + 2)
Run Code Online (Sandbox Code Playgroud)
该包提供了查找任意阶多项式的所有(实数和复数)根的PolynomialRoots.jl函数。roots()唯一的强制参数是包含多项式系数按升序排列的数组。
例如,为了找到根
6x^5 + 5x^4 + 3x^2 + 2x + 1
Run Code Online (Sandbox Code Playgroud)
加载包(using PolynomialRoots)后您可以使用
6x^5 + 5x^4 + 3x^2 + 2x + 1
Run Code Online (Sandbox Code Playgroud)
该包是本文中描述的寻根算法的 Julia 实现:http://arxiv.org/abs/1203.1034
PolynomialRoots.jl还支持任意精度计算。这对于求解无法以双精度求解的方程非常有用。例如
julia> roots([1, 2, 3, 4, 5, 6])
5-element Array{Complex{Float64},1}:
0.294195-0.668367im
-0.670332+2.77556e-17im
0.294195+0.668367im
-0.375695-0.570175im
-0.375695+0.570175im
Run Code Online (Sandbox Code Playgroud)
给出多项式的错误结果,而是以任意精度传递输入数组,强制提供正确答案的任意精度计算(请参阅https://en.wikipedia.org/wiki/Loss_of_significance):
julia> r = roots([94906268.375, -189812534, 94906265.625]);
julia> (r[1], r[2])
(1.0000000144879793 - 0.0im,1.0000000144879788 + 0.0im)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1270 次 |
| 最近记录: |