<jupyter_start><jupyter_text>Monte Carlo approximation on Uniform distribution<jupyter_code>import jax.numpy as jnp
from jax import random


import matplotlib.pyplot as plt
import seaborn as sns

try:
    from probml_utils import savefig, latexify, is_latexify_enabled
except:
    %pip install git+https://github.com/probml/probml-utils.git
    from probml_utils import savefig, latexify, is_latexify_enabled
latexify(width_scale_factor=1, fig_height=2)
x_samples = jnp.linspace(-1, 1, 200)
lower_limit = -1
upper_limit = 1
px_uniform = 1 / (upper_limit - lower_limit) * jnp.ones(len(x_samples))

square_fn = lambda x: x**2
y = square_fn(x_samples)

# analytic
y_pdf = 1 / (2 * jnp.sqrt(y + 1e-2))

# monte carlo
n = 1000

key = random.PRNGKey(0)
uniform_samples = random.uniform(key, shape=(n, 1), minval=lower_limit, maxval=upper_limit)
fn_samples = square_fn(uniform_samples)


print(jnp.mean(fn_samples))
if not is_latexify_enabled():
    fig, ax = plt.subplots(nrows=1, ncols=3, figsize=(15, 3))
else:
    fig, ax = plt.subplots(nrows=1, ncols=3)

ax[0].set_title("Uniform distribution")
ax[0].plot(x_samples, px_uniform, "-")
ax[0].set_xlabel("$x$")
ax[0].set_ylabel("$p(x)$")


ax[1].set_title("Analytical p(y), $y(x)$ = $x^2$")
ax[1].plot(y, y_pdf, "-", linewidth=2)
ax[1].set_xlabel("$y$")
ax[1].set_ylabel("$p(y)$")

ax[2].set_title("Monte carlo approximation")
sns.distplot(fn_samples, kde=False, ax=ax[2], bins=20, norm_hist=True, hist_kws=dict(edgecolor="k", linewidth=1))
ax[2].set_xlabel("$y$")
ax[2].set_ylabel("$Frequency$")


sns.despine()
savefig("changeOfVars")
plt.show()<jupyter_output>/home/rohit_khoiwal/.local/lib/python3.8/site-packages/seaborn/distributions.py:2619: FutureWarning: `distplot` is a deprecated function and will be removed in a future version. Please adapt your code to use either `displot` (a figure-level function with similar flexibility) or `histplot` (an axes-level function for histograms).
  warnings.warn(msg, FutureWarning)
/home/rohit_khoiwal/.local/lib/python3.8/site-packages/probml_utils/plotting.py:79: UserWarning: set FIG_DIR environment variable to save figures
  warnings.warn("set FIG_DIR environment variable to save figures")
{'fraction_non_alphanumeric': 0.14579524680073125, 'fraction_numerical': 0.025137111517367458, 'mean_word_length': 6.084142394822006, 'pattern_counts': {'":': 0, '<': 4, '<?xml version=': 0, '>': 4, 'https://': 1, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '1', 'dir': 'jupyter-structured-clean-dedup', 'id': '273708', 'license': 'MIT', 'n_tokens_mistral': 872, 'n_tokens_neox': 837, 'n_words': 177, 'path': 'notebooks/book1/02/change_of_vars_demo1d.ipynb', 'repo_name': 'patel-zeel/pyprobml', 'size': '2188'}