Skip to content

Commit a2b37bf

Browse files
committed
add derivatives
1 parent c8953dd commit a2b37bf

File tree

1 file changed

+41
-4
lines changed

1 file changed

+41
-4
lines changed

sandpit/cons_smooth_tom_v2.md

Lines changed: 41 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -469,22 +469,59 @@ plt.show()
469469

470470
+++ {"user_expressions": []}
471471

472-
We can even use the Python numpy grad command to compute derivatives of welfare with respect to our two parameters.
472+
We can even use the Python `np.gradient` command to compute derivatives of welfare with respect to our two parameters.
473473

474474
We are teaching the key idea beneath the **calculus of variations**.
475475

476+
First, we define the welfare with respect to $\xi_1$ and $\phi$
477+
476478
```{code-cell} ipython3
477-
def welfare_ϕ(ξ1, ϕ):
479+
def welfare_rel(ξ1, ϕ):
478480
"Compute welfare of variation sequence for given ϕ, ξ1 with a consumption smoothing model"
479481
cvar_seq = compute_variation(cs_model, ξ1=ξ1, ϕ=ϕ, a0=a0,
480482
y_seq=y_seq, verbose=0)
481483
return welfare(cs_model, cvar_seq)
482484
483-
welfare_ϕ_vec = np.vectorize(welfare_ϕ)
485+
# Vectorize the function to allow array input
486+
welfare_vec = np.vectorize(welfare_rel)
487+
```
488+
489+
+++ {"user_expressions": []}
490+
491+
Then we can visualize the relationship between welfare and $\xi_1$ and compute its derivatives
492+
493+
```{code-cell} ipython3
484494
ξ1_arr = np.linspace(-0.5, 0.5, 20)
485495
486-
plt.plot(ξ1_arr, welfare_ϕ_vec(ξ1_arr, 1.02))
496+
plt.plot(ξ1_arr, welfare_vec(ξ1_arr, 1.02))
487497
plt.ylabel('welfare')
488498
plt.xlabel(r'$\xi_1$')
489499
plt.show()
500+
501+
welfare_grad = welfare_vec(ξ1_arr, 1.02)
502+
welfare_grad = np.gradient(welfare_grad)
503+
plt.plot(ξ1_arr, welfare_grad)
504+
plt.ylabel('derivatives of welfare')
505+
plt.xlabel(r'$\xi_1$')
506+
plt.show()
507+
```
508+
509+
+++ {"user_expressions": []}
510+
511+
The same can be done on $\phi$
512+
513+
```{code-cell} ipython3
514+
ϕ_arr = np.linspace(-0.5, 0.5, 20)
515+
516+
plt.plot(ξ1_arr, welfare_vec(0.05, ϕ_arr))
517+
plt.ylabel('welfare')
518+
plt.xlabel(r'$\phi$')
519+
plt.show()
520+
521+
welfare_grad = welfare_vec(0.05, ϕ_arr)
522+
welfare_grad = np.gradient(welfare_grad)
523+
plt.plot(ξ1_arr, welfare_grad)
524+
plt.ylabel('derivatives of welfare')
525+
plt.xlabel(r'$\phi$')
526+
plt.show()
490527
```

0 commit comments

Comments
 (0)