在摘自:https://tutorials.sciml.ai/html/models/01-classical_physics.html的代码中,如下所示:
# Simple Harmonic Oscillator Problem
using OrdinaryDiffEq, Plots
# Parameters
ω = 1
# Initial Conditions
x₀ = [0.0]
dx₀ = [π/2]
tspan = (0.0, 2π)
ϕ = atan((dx₀[1]/ω)/x₀[1])
A = √(x₀[1]^2 + dx₀[1]^2)
# Define the problem
function harmonicoscillator(ddu,du,u,ω,t)
ddu .= -ω^2 * u
end
# Pass to solvers
prob = SecondOrderODEProblem(harmonicoscillator, dx₀, x₀, tspan, ω)
sol = solve(prob, DPRKN6())
# Plot
plot(sol, vars=[2,1], linewidth=2, title ="Simple Harmonic Oscillator", xaxis = "Time", yaxis = "Elongation", label = ["x" "dx"])
plot!(t->A*cos(ω*t-ϕ), lw=3, ls=:dash, label="Analytical Solution x")
plot!(t->-A*ω*sin(ω*t-ϕ), lw=3, ls=:dash, label="Analytical Solution dx")我不明白.=算子在函数谐振子中的用法。使用=给了我错误的答案。所以,我想知道.=和=有什么不同?它不是矢量化的ddu,因为RHS都是标量。
发布于 2021-04-24 15:17:21
我不明白.=算子在函数谐振子中的用法。..。它不是矢量化ddu,因为RHS都是标量。
是的;u、du和ddu不是标量,它们是长度-1向量.
您可以问朱莉娅.=语法是什么意思:
julia> Meta.@lower a .= b
:($(Expr(:thunk, CodeInfo(
@ none within `top-level scope'
1 ─ %1 = Base.broadcasted(Base.identity, b)
│ %2 = Base.materialize!(a, %1)
└── return %2
))))这看起来有点牵扯,但本质上是一项广播任务,类似于
for i in eachindex(a, b)
a[i] = b[i]
end使用=给了我错误的答案。
是的,因为DiffEq库要求函数harmonicoscillator修改输入。如果只使用=,则创建一个与该函数局部的新变量,而不是修改输入向量,这在外部是不可见的。
https://stackoverflow.com/questions/67242453
复制相似问题