Julia中微分方程函数将输出写入首个输入的技术疑问
Great question—this is a common point of confusion when first working with SciML's differential equation solvers, and it all boils down to performance through minimizing memory allocation. Let me break this down step by step:
What's the "du as first input" pattern?
This is called an in-place function (or "mutating function" in Julia terms). Instead of creating and returning a new array with the computed derivatives, the function modifies an existing array (du) that's passed to it as the first argument. The function doesn't need to return anything (though it implicitly returns nothing), because the solver will read the results directly from the modified du array.
Why does this matter for array allocation?
When you write a "non-in-place" function that returns a new array (like below):
function lorenz(u,p,t) return [10.0*(u[2]-u[1]), u[1]*(28.0-u[3]) - u[2], u[1]*u[2] - (8/3)*u[3]] end
every time the solver calls this function, Julia has to allocate a brand new 3-element array to hold the derivatives. For an ODE solver that might call this function thousands or millions of times during integration, all those repeated allocations add up:
- They consume extra memory
- They trigger frequent garbage collection (GC) pauses, which slow down your code
By using the in-place pattern, the solver can pre-allocate a single du array once at the start of the integration. Every time it calls lorenz(du,u,p,t), it reuses that same array—no new memory is allocated, and no GC is needed for these derivative calculations. This leads to massive speedups, especially for large systems of ODEs.
How does this work with the Lorenz example?
In your code:
function lorenz(du,u,p,t) du[1] = 10.0*(u[2]-u[1]) du[2] = u[1]*(28.0-u[3]) - u[2] du[3] = u[1]*u[2] - (8/3)*u[3] end
- The solver creates the
duarray before starting the integration - Each time it needs to compute the derivatives, it passes this pre-allocated
duto your function - Your function writes the derivative values directly into
du's existing memory slots - The solver uses the updated
duto take the next step in the integration
Is the non-in-place option still available?
Absolutely! SciML solvers do support non-in-place functions (returning a new array) for convenience, especially for small systems or prototyping. But for production code or performance-critical simulations, the in-place pattern is strongly recommended.
内容的提问来源于stack exchange,提问作者MOON

