# How to use DifferentialEquations.jl to do a Monte Carlo

**URL:** <https://discourse.julialang.org/t/how-to-use-differentialequations-jl-to-do-a-monte-carlo/97450>\
**Category:** Numerics\
**Created:** [April 13, 2023, 9:36pm UTC](https://discourse.julialang.org/t/how-to-use-differentialequations-jl-to-do-a-monte-carlo/97450 "2023-04-13T21:36:48Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![marcofrancis](https://avatars.discourse-cdn.com/v4/letter/m/bcef8e/32.png) [@marcofrancis](https://discourse.julialang.org/u/marcofrancis)\
**Post date:** [April 13, 2023, 9:36pm UTC](https://discourse.julialang.org/t/how-to-use-differentialequations-jl-to-do-a-monte-carlo/97450/1 "2023-04-13T21:36:48Z")

</div>

Hi,  
I managed to simulate (with `EnsembleProblem` ) 1000 paths of a 2-dimensional SDE. Let’s call the one dimensional components x(t) and y(t). I have some problems handling the solution to the problem: the paths are of different lengths ( hence I cannot call Array(sol) ) and the solutions’ “u” are computed at different times, is this normal as the default behaviour?. I’d like to know how to get for each path the cumulative time integral of x(t)\*y(t), and then compute the Monte Carlo average across the paths.  
I include some code for reference:

```julia
X₀ = [0.01, p.ωb]
prob_x = SDEProblem(μ, Σ, X₀, T_span, p, noise_rate_prototype = zeros(2, 2))
ensembleprob = EnsembleProblem(prob_x)
sol_SDE = solve(ensembleprob, EnsembleThreads(), trajectories = 1000)

```

---

<div class="post-metadata">

**Author:** ![ChrisRackauckas](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/chrisrackauckas/32/77_2.png) [@ChrisRackauckas](https://discourse.julialang.org/u/ChrisRackauckas)\
**Post date:** [April 14, 2023, 10:51am UTC](https://discourse.julialang.org/t/how-to-use-differentialequations-jl-to-do-a-monte-carlo/97450/2 "2023-04-14T10:51:07Z")

</div>

> [@marcofrancis](#):
>
> the paths are of different lengths ( hence I cannot call Array(sol) ) and the solutions’ “u” are computed at different times, is this normal as the default behaviour?

Yes, if you use adaptive time stepping then they will be calculated at different times. If you want it to save all at the same times, use `saveat.` For example:

```julia
sol_SDE = solve(ensembleprob, EnsembleThreads(), trajectories = 1000, saveat = 0.1)

```

saves at every dt=0.1. For more information, see the output control options in:

> **[Common Solver Options (Solve Keyword Arguments) · DifferentialEquations.jl](https://docs.sciml.ai/DiffEqDocs/stable/basics/common_solver_opts/)**
>
> Documentation for DifferentialEquations.jl.

> [@marcofrancis](#):
>
> I’d like to know how to get for each path the cumulative time integral of x(t)\*y(t)

The best thing to do is just add a psuedo term to the SDE that is `du[3] = u[1]*u[2]`, and thus u[3] is the integral.
