GitHub

Original file line numberDiff line numberDiff line change

@@ -832,16 +832,31 @@ def compute_call_price_jax(β=β,

832832
833833

s = jnp.full(M, np.log(S0))

834834

h = jnp.full(M, h0)

835-

for t in range(n):

835+
836+

def update(i, loop_state):

837+

s, h, key = loop_state

836838

key, subkey = jax.random.split(key)

837839

Z = jax.random.normal(subkey, (2, M))

838840

s = s + μ + jnp.exp(h) * Z[0, :]

839841

h = ρ * h + ν * Z[1, :]

842+

new_loop_state = s, h, key

843+

return new_loop_state

844+
845+

initial_loop_state = s, h, key

846+

final_loop_state = jax.lax.fori_loop(0, n, update, initial_loop_state)

847+

s, h, key = final_loop_state

848+
840849

expectation = jnp.mean(jnp.maximum(jnp.exp(s) - K, 0))

841850
842851

return β**n * expectation

843852

```

844853
854+

```{note}

855+

We use `jax.lax.fori_loop` instead of a Python `for` loop.

856+

This allows JAX to compile the loop efficiently without unrolling it,

857+

which significantly reduces compilation time for large arrays.

858+

```

859+
845860

Let's run it once to compile it:

846861
847862

```{code-cell} ipython3

Read the original on github.com ↗