【问题标题】:Deflation Method for Multiple Root Finding寻找多根的紧缩法
【发布时间】:2020-09-14 16:45:48
【问题描述】:

我正在尝试实现 deflation method 以在 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)

【问题讨论】:

  • 您应该尝试发布我们可以在我们自己的系统上重现的最小(非)工作示例。例如,您的代码(就目前而言)包含一些与您的问题完全无关的错误:从未调用g,未定义a 和Muller_method,deflation 函数定义缺少@ 987654329@关键字...有一个可重复的例子将帮助我们帮助你!
  • 顺便说一句,使用[] 初始化无类型数组通常不是一个好主意。如果您知道 roots 将只包含浮点数,最好像这样初始化它,例如:roots = Float64[]。
  • 我没有分享那部分,因为我认为它没有错。我很抱歉这是我的第一篇文章。非常感谢。

标签: julia numerical-methods


【解决方案1】:

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

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

【讨论】:

  • 非常感谢。我不知道减少方法。再次对我有很大帮助,谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多