@@ -832,16 +832,31 @@ def compute_call_price_jax(β=β,
|
832 | 832 | |
833 | 833 | s = jnp.full(M, np.log(S0)) |
834 | 834 | h = jnp.full(M, h0) |
835 | | - for t in range(n): |
| 835 | + |
| 836 | + def update(i, loop_state): |
| 837 | + s, h, key = loop_state |
836 | 838 | key, subkey = jax.random.split(key) |
837 | 839 | Z = jax.random.normal(subkey, (2, M)) |
838 | 840 | s = s + μ + jnp.exp(h) * Z[0, :] |
839 | 841 | 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 | + |
840 | 849 | expectation = jnp.mean(jnp.maximum(jnp.exp(s) - K, 0)) |
841 | 850 | |
842 | 851 | return β**n * expectation |
843 | 852 | ``` |
844 | 853 | |
| 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 | + |
845 | 860 | Let's run it once to compile it: |
846 | 861 | |
847 | 862 | ```{code-cell} ipython3 |
|