我试图用Julia写一个函数,用牛顿迭代法求解非线性方程f(x)=0。我是朱莉娅的初学者,所以请容忍我。在作业中,我的导师提供了第一行代码:
newton(f, x_0; maxiterations=10, tolerance=1e-14, epsilon=1e-7)他还提供了这样的说法:“可选的epsilon参数提供了在有限差分近似f‘(X)≈(f(x +ε)−f(x)) /ε中使用的值。”在过去,我在MATLAB中为牛顿方法创建了一个函数,但我假设f(x)的一阶导数必须是函数的输入之一。在这个作业中,他似乎想让我使用这个近似公式。不管怎样,到目前为止,这是我的代码。
function newton(f,x_0; maxiterations=10, tolerance=1e-14, epsilon=1e-7)
x = [x_0] # assign x_0 to x and make x a vector
fd = (f(x.+epsilon) - f(x))./epsilon # fd is the first derivative of f(x), calculated from
# the finite-difference approximation
# create for loop to begin iteration
for n = 0:maxiterations
if abs(x[n+1]-x[n]) < tolerance # if the absolute value of the difference of x[n+1] and x[n]
# is less than the tolerance, then the value of x is returned
return x
end
if abs(f(x[n])) < tolerance # if the absolute value of f(x[n]) is less than the tolerance,
# then the value of x is returned
return x
end
push!(x, x[n] - (f(x[n]))/fd) # push each calculated value to the end of vector x,
# and continue iterating
end
return x # after iteration is complete, return the vector x
end在执行这个函数之后,我定义了用于确定sqrt(13)的方程,并用x_0=3的初始猜测调用了牛顿函数。
f(x) = x^2 - 13
newton(f,3)下面是在调用newton函数之后遇到的错误消息:
MethodError: no method matching ^(::Vector{Float64}, ::Int64)
Closest candidates are:
^(::Union{AbstractChar, AbstractString}, ::Integer) at strings/basic.jl:730
^(::LinearAlgebra.Hermitian, ::Integer) at /Applications/Julia-1.8.app/Contents/Resources/julia/share/julia/stdlib/v1.8/LinearAlgebra/src/symmetric.jl:696
^(::LinearAlgebra.Hermitian{T, S} where S<:(AbstractMatrix{<:T}), ::Real) where T at /Applications/Julia-1.8.app/Contents/Resources/julia/share/julia/stdlib/v1.8/LinearAlgebra/src/symmetric.jl:707
...
Stacktrace:
[1] literal_pow
@ ./intfuncs.jl:340 [inlined]
[2] f(x::Vector{Float64})
@ Main ./In[35]:3
[3] newton(f::typeof(f), x_0::Int64; maxiterations::Int64, tolerance::Float64, epsilon::Float64)
@ Main ./In[34]:5
[4] newton(f::Function, x_0::Int64)
@ Main ./In[34]:2
[5] top-level scope
@ In[35]:4
[6] eval
@ ./boot.jl:368 [inlined]
[7] include_string(mapexpr::typeof(REPL.softscope), mod::Module, code::String, filename::String)
@ Base ./loading.jl:1428在这个问题中,我应该让我的函数返回一个连续逼近的向量,并绘制一个对数误差图,其中包括牛顿迭代的理论误差估计曲线。我希望在纠正代码中的问题方面提供任何指导,这样我就可以继续创建错误图了。
谢谢。
发布于 2022-09-09 23:22:29
您可以使用
newton(x->x.^2 .- 13, 3.)用矢量代替标量来操作矢量。但你的牛顿密码还被窃听了!
从零索引开始(不好),在分配之前使用xn+1,它缺少一些数学步骤。我可以向你求婚
function newton(f,x_0; maxiterations=10, tolerance=1e-14, epsilon=1e-7)
x = x_0
iterates = [x]; # iterates will store the iterates' sequence
# create for loop to begin iteration
for n =1:maxiterations
fd = (f(x.+epsilon) - f(x))./epsilon
tmp=x - f(x) / fd
if (abs(tmp-x) < tolerance || abs(f(x)) < tolerance )
break
end
x = tmp
push!(iterates,x)
end
return iterates
end现在看来效果很好
julia> newton(x->x.^2 .- 13, 3.)
5-element Vector{Float64}:
3.0
3.6666666569022053
3.6060606066709835
3.605551311439882
3.60555127546399https://stackoverflow.com/questions/73668047
复制相似问题