首页 > 解决方案 > 寻找多根的紧缩法

问题描述

我正在尝试实现 通货紧缩方法以在 Julia 上查找多项式的多个根。在deflation方法中,新函数是由实际函数除以 生成的x - x_roots[i],并且必须找到新生成函数的根。但是g(x) = g(x) / (x - x_root) 给了我一个堆栈溢出错误,因为它可能生成了一个无限递归关系。如何在每个步骤中生成一个新函数?

function deflation(f::Function, order)
    roots=[]
    n=1
    g(x)=f(x)
    x_root=Muller_method(f,-5,0,5,1e-5,50)
    while n<=order
        x_root=Muller_method(a,-5,0,5,1e-5,50)
        g(x)=g(x)/(x-x_root)
        append!(roots,x_root)
        n=n+1
    end
return (roots)

标签: julianumerical-methods

解决方案


这样的事情会导致无限递归:

julia> g(x) = x
g (generic function with 1 method)

julia> g(1)
1

julia> g(x) = g(x) / 2
g (generic function with 1 method)

julia> g(1)
ERROR: StackOverflowError:
Stacktrace:
 [1] g(::Int64) at ./REPL[3]:1 (repeats 79984 times)

这是因为函数(或方法)定义不像变量赋值那样工作:每次重新定义都会g(x)覆盖前一个(注意g上面只有一个方法)。当一个方法定义引用它自己时,它是递归的,即在函数被调用时它引用它自己的版本。


至于你的通货紧缩方法,也许你可以定义一个新函数来关闭当前找到的根的向量。考虑下面的例子来看看事情是如何工作的:

julia> f(x) = (x-1) * (x-2)
f (generic function with 1 method)

julia> roots = Float64[]
Float64[]


# g is defined once, and accounts for all currently found roots
julia> g(x) = f(x) / reduce(*, x-root for root in roots; init=one(x))
g (generic function with 1 method)


# No roots are identified at the beginning
julia> g(1+eps())  
-2.2204460492503126e-16

julia> g(2+eps())
0.0


# But the results produced by g update as roots are identified
julia> push!(roots, 1.)
1-element Array{Float64,1}:
 1.0

julia> g(1+eps())
-0.9999999999999998

julia> g(2+eps())
0.0

推荐阅读