julia - 寻找多根的紧缩法
问题描述
我正在尝试实现 通货紧缩方法以在 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)
解决方案
这样的事情会导致无限递归:
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
推荐阅读
- sql - 根据每条记录的最近日期连接表
- sharepoint - SharePoint 2016 补丁建议
- python - 折线图未在多页绘图破折号上显示数据
- curl - CompactToken 解析失败,错误代码:80049217 - cURL Microsoft Graph API
- salesforce-lightning - 在 Salesforce 中完成嵌套 IF 公式时遇到问题
- python - 如何使用 to_datetime 永久更改 Pandas 列,以便写入 .json 文件
- c++ - 使用“this”指针返回类成员指针变量的值
- kubernetes - 为什么 DigitalOcean k8s 节点容量显示从节点池配置中减去的值?
- python - 一个变量是函数的局部变量,只要它的值写在函数内部的任何地方?
- angular - 未捕获(承诺中):错误:模块“ModalModule”导入的意外值“Ng2SmartTableModule”。请添加@NgModule 注释