Refactor code for improved readability and consistency across notebooks

- Standardized spacing around operators and function arguments in TP7_Kmeans.ipynb and neural_network.ipynb.
- Enhanced the formatting of model building and training code in neural_network.ipynb for better clarity.
- Updated the pyproject.toml to remove a specific TensorFlow version and added linting configuration for Ruff.
- Improved comments and organization in the code to facilitate easier understanding and maintenance.
This commit is contained in:
2025-07-01 20:46:08 +02:00
parent e273cf90f7
commit f94ff07cab
34 changed files with 5713 additions and 5047 deletions

View File

@@ -122,7 +122,7 @@
" y = np.zeros(N + 1)\n",
" y[0] = y0\n",
" for n in range(N):\n",
" y[n + 1] = np.power(h + np.sqrt(h ** 2 + y[n]), 2)\n",
" y[n + 1] = np.power(h + np.sqrt(h**2 + y[n]), 2)\n",
" return t, y"
]
},
@@ -158,7 +158,7 @@
"\n",
"plt.scatter(t, sol_appr, label=\"Approximation with EI\")\n",
"plt.plot(x, f_exact(x, T), label=\"Exact solution\", color=\"red\")\n",
"plt.plot(x, x ** 2, label=\"Square function\", color=\"green\")\n",
"plt.plot(x, x**2, label=\"Square function\", color=\"green\")\n",
"plt.legend()\n",
"plt.show()"
]
@@ -297,9 +297,9 @@
"\n",
"sol = odeint(F, y0, t, args=(a, r))\n",
"\n",
"plt.plot(t, sol[:, 0], label='S(t)')\n",
"plt.plot(t, sol[:, 1], label='I(t)')\n",
"plt.plot(t, sol[:, 2], label='R(t)')\n",
"plt.plot(t, sol[:, 0], label=\"S(t)\")\n",
"plt.plot(t, sol[:, 1], label=\"I(t)\")\n",
"plt.plot(t, sol[:, 2], label=\"R(t)\")\n",
"plt.legend()\n",
"plt.show()"
]
@@ -336,7 +336,9 @@
"\n",
"def calculate_errors(sol_exact, sol_appr):\n",
" return np.max(\n",
" np.power(np.abs(sol_appr - sol_exact), 2)[np.isfinite(np.power(np.abs(sol_appr - sol_exact), 2))]\n",
" np.power(np.abs(sol_appr - sol_exact), 2)[\n",
" np.isfinite(np.power(np.abs(sol_appr - sol_exact), 2))\n",
" ]\n",
" )\n",
"\n",
"\n",
@@ -356,8 +358,8 @@
"plt.plot(errors_EE, label=\"Euler Explicit\")\n",
"plt.plot(errors_H, label=\"Heun\")\n",
"plt.plot(errors_RK4, label=\"Runge Kutta order 4\")\n",
"plt.yscale('log')\n",
"plt.xscale('log')\n",
"plt.yscale(\"log\")\n",
"plt.xscale(\"log\")\n",
"plt.legend()\n",
"plt.show()"
]
@@ -431,23 +433,23 @@
"# Plot the real parts\n",
"plt.figure(figsize=(12, 6))\n",
"plt.subplot(1, 2, 1)\n",
"plt.plot(t, np.real(x_appr_EI), label='Numerical Solution by EI')\n",
"plt.plot(t, np.real(x_appr_EE), label='Numerical Solution by EE')\n",
"plt.plot(t, np.real(x_exact), label='Exact Solution', linestyle='--')\n",
"plt.xlabel('Time')\n",
"plt.ylabel('Real Part')\n",
"plt.plot(t, np.real(x_appr_EI), label=\"Numerical Solution by EI\")\n",
"plt.plot(t, np.real(x_appr_EE), label=\"Numerical Solution by EE\")\n",
"plt.plot(t, np.real(x_exact), label=\"Exact Solution\", linestyle=\"--\")\n",
"plt.xlabel(\"Time\")\n",
"plt.ylabel(\"Real Part\")\n",
"plt.legend()\n",
"plt.title('Real Part of the Solution')\n",
"plt.title(\"Real Part of the Solution\")\n",
"\n",
"# Plot the imaginary parts\n",
"plt.subplot(1, 2, 2)\n",
"plt.plot(t, np.imag(x_appr_EI), label='Numerical Solution by EI')\n",
"plt.plot(t, np.imag(x_appr_EE), label='Numerical Solution by EE')\n",
"plt.plot(t, np.imag(x_exact), label='Exact Solution', linestyle='--')\n",
"plt.xlabel('Time')\n",
"plt.ylabel('Imaginary Part')\n",
"plt.plot(t, np.imag(x_appr_EI), label=\"Numerical Solution by EI\")\n",
"plt.plot(t, np.imag(x_appr_EE), label=\"Numerical Solution by EE\")\n",
"plt.plot(t, np.imag(x_exact), label=\"Exact Solution\", linestyle=\"--\")\n",
"plt.xlabel(\"Time\")\n",
"plt.ylabel(\"Imaginary Part\")\n",
"plt.legend()\n",
"plt.title('Imaginary Part of the Solution')\n",
"plt.title(\"Imaginary Part of the Solution\")\n",
"\n",
"plt.show()"
]

View File

@@ -1,8 +1,9 @@
{
"cells": [
{
"metadata": {},
"cell_type": "markdown",
"id": "c897654e0a140cbd",
"metadata": {},
"source": [
"# Automatic Differentiation\n",
"\n",
@@ -11,42 +12,18 @@
"Loss function: softmax layer in $\\mathbb{R}^3$\n",
"\n",
"Architecture: FC/ReLU 4-5-7-3"
],
"id": "c897654e0a140cbd"
]
},
{
"cell_type": "code",
"execution_count": 33,
"id": "70a4eb1d928b10d0",
"metadata": {
"ExecuteTime": {
"end_time": "2025-03-24T15:16:27.015669Z",
"start_time": "2025-03-24T15:16:23.856887Z"
}
},
"cell_type": "code",
"source": [
"import numpy as np\n",
"from sklearn.neural_network import MLPClassifier\n",
"from sklearn.datasets import make_classification\n",
"from sklearn.model_selection import train_test_split\n",
"from sklearn.metrics import accuracy_score\n",
"\n",
"accuracies = []\n",
"\n",
"for _ in range(10):\n",
" X, y = make_classification(n_samples=1000, n_features=4, n_classes=3, n_clusters_per_class=1)\n",
"\n",
" X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)\n",
" model = MLPClassifier(hidden_layer_sizes=(5, 7), activation='relu', max_iter=10000, solver='adam')\n",
" model.fit(X_train, y_train)\n",
"\n",
" y_pred = model.predict(X_test)\n",
" accuracies.append(accuracy_score(y_test, y_pred))\n",
"\n",
"print(f'Mean Accuracy: {np.mean(accuracies) * 100:.0f}%')\n",
"print(f'STD Accuracy: {np.std(accuracies) * 100:.0f}%')\n",
"print(f\"Max accuracy: {np.max(accuracies) * 100:.0f}%\")\n",
"print(f\"Min accuracy: {np.min(accuracies) * 100:.0f}%\")"
],
"id": "70a4eb1d928b10d0",
"outputs": [
{
"name": "stdout",
@@ -59,20 +36,47 @@
]
}
],
"execution_count": 33
"source": [
"import numpy as np\n",
"from sklearn.neural_network import MLPClassifier\n",
"from sklearn.datasets import make_classification\n",
"from sklearn.model_selection import train_test_split\n",
"from sklearn.metrics import accuracy_score\n",
"\n",
"accuracies = []\n",
"\n",
"for _ in range(10):\n",
" X, y = make_classification(\n",
" n_samples=1000, n_features=4, n_classes=3, n_clusters_per_class=1\n",
" )\n",
"\n",
" X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)\n",
" model = MLPClassifier(\n",
" hidden_layer_sizes=(5, 7), activation=\"relu\", max_iter=10000, solver=\"adam\"\n",
" )\n",
" model.fit(X_train, y_train)\n",
"\n",
" y_pred = model.predict(X_test)\n",
" accuracies.append(accuracy_score(y_test, y_pred))\n",
"\n",
"print(f\"Mean Accuracy: {np.mean(accuracies) * 100:.0f}%\")\n",
"print(f\"STD Accuracy: {np.std(accuracies) * 100:.0f}%\")\n",
"print(f\"Max accuracy: {np.max(accuracies) * 100:.0f}%\")\n",
"print(f\"Min accuracy: {np.min(accuracies) * 100:.0f}%\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "96b6d46883ed5570",
"metadata": {
"ExecuteTime": {
"end_time": "2025-03-24T14:37:53.507776Z",
"start_time": "2025-03-24T14:37:53.505376Z"
}
},
"cell_type": "code",
"source": "",
"id": "96b6d46883ed5570",
"outputs": [],
"execution_count": null
"source": []
}
],
"metadata": {

View File

@@ -51,17 +51,18 @@
" \"\"\"\n",
" return S0 * np.exp((mu - 0.5 * sigma**2) * t + sigma * W)\n",
"\n",
"\n",
"def euler_maruyama(mu, sigma, T, N, X0=0.0):\n",
" \"\"\"\n",
" Simulation d'une EDS de Black-Scholes par la méthode d'Euler-Maruyama\n",
" \n",
"\n",
" Paramètres :\n",
" mu (float) : drift\n",
" sigma (float) : volatilité\n",
" T (int) : temps final\n",
" N (int) : nombre de pas de temps\n",
" X0 (float) : valeur initiale\n",
" \n",
"\n",
" Retourne :\n",
" t (array-like) : tableau des temps\n",
" X (array-like) : tableau des valeurs de l'EDS\n",
@@ -70,17 +71,18 @@
"\n",
" t = np.linspace(0, T, N + 1)\n",
" X = np.zeros(N + 1)\n",
" \n",
"\n",
" X[0] = X0\n",
"\n",
" dW = np.random.normal(0, np.sqrt(dt), N)\n",
" \n",
"\n",
" for i in range(N):\n",
" St = S(t[i], X[i], mu, sigma, dW[i])\n",
" X[i + 1] = X[i] + mu * St * dt + sigma * St * dW[i]\n",
" \n",
"\n",
" return t, X\n",
"\n",
"\n",
"def plot_brownien(t, X, B=None):\n",
" \"\"\"\n",
" Plot la simulation d'Euler-Maruyama\n",
@@ -90,15 +92,15 @@
" X (array-like) : tableau des valeurs de l'EDS\n",
" B (float) : barrière (optionnelle)\n",
" \"\"\"\n",
" plt.plot(t, X, alpha=0.5, label='Euler-Maruyama')\n",
" plt.title('Simulation d\\'Euler-Maruyama pour une EDS')\n",
" \n",
" plt.plot(t, X, alpha=0.5, label=\"Euler-Maruyama\")\n",
" plt.title(\"Simulation d'Euler-Maruyama pour une EDS\")\n",
"\n",
" if B is not None:\n",
" plt.axhline(B, label='Barrière', color='red', linestyle='--')\n",
" \n",
" plt.axhline(B, label=\"Barrière\", color=\"red\", linestyle=\"--\")\n",
"\n",
" plt.legend()\n",
" plt.xlabel('Temps')\n",
" plt.ylabel('X(t)')\n",
" plt.xlabel(\"Temps\")\n",
" plt.ylabel(\"X(t)\")\n",
" plt.grid()"
]
},
@@ -165,10 +167,11 @@
"\n",
"np.random.seed(333)\n",
"\n",
"\n",
"def plot_convergence(S0, mu, sigma, T):\n",
" \"\"\"\n",
" Plot la convergence du schéma d'Euler-Maruyama\n",
" \n",
"\n",
" Paramètres :\n",
" S0 (int) : valeur initiale\n",
" mu (float) : drift\n",
@@ -176,26 +179,27 @@
" T (int) : temps final\n",
" \"\"\"\n",
" errors = []\n",
" \n",
"\n",
" for N in N_list:\n",
" dt = T / N\n",
" dW = np.random.normal(0, np.sqrt(dt), N)\n",
" \n",
"\n",
" exact = S(T, S0, mu, sigma, dW)\n",
" _, X = euler_maruyama(mu=mu, sigma=sigma, T=T, N=N, X0=S0)\n",
" \n",
"\n",
" errors.append(np.max(np.abs(X[1:] - exact)))\n",
" \n",
" plt.plot(np.log(h_list), np.log(errors), 'o-', label='Erreur numérique')\n",
" plt.plot(np.log(h_list), 0.5 * np.log(h_list), '--', label='Ordre 1/2')\n",
" plt.plot(np.log(h_list), np.log(h_list), '--', label='Ordre 1')\n",
" plt.plot(np.log(h_list), 2*np.log(h_list), '--', label='Ordre 2')\n",
" plt.xlabel('log(h)')\n",
" plt.ylabel('log(Erreur)')\n",
" plt.title('Convergence du schéma d\\'Euler-Maruyama')\n",
"\n",
" plt.plot(np.log(h_list), np.log(errors), \"o-\", label=\"Erreur numérique\")\n",
" plt.plot(np.log(h_list), 0.5 * np.log(h_list), \"--\", label=\"Ordre 1/2\")\n",
" plt.plot(np.log(h_list), np.log(h_list), \"--\", label=\"Ordre 1\")\n",
" plt.plot(np.log(h_list), 2 * np.log(h_list), \"--\", label=\"Ordre 2\")\n",
" plt.xlabel(\"log(h)\")\n",
" plt.ylabel(\"log(Erreur)\")\n",
" plt.title(\"Convergence du schéma d'Euler-Maruyama\")\n",
" plt.legend()\n",
" plt.grid(True)\n",
"\n",
"\n",
"plt.figure(figsize=(10, 5))\n",
"plot_convergence(S0, r, sigma, T)\n",
"plt.show()"
@@ -269,6 +273,7 @@
"plot_brownien(t, X, B=B)\n",
"plt.show()\n",
"\n",
"\n",
"def is_barrier_breached(X, B):\n",
" \"\"\"Renvoie True si la barrière est franchie, False sinon\n",
" La barrière est franchie si X >= B\n",
@@ -282,7 +287,12 @@
" \"\"\"\n",
" return any(X >= B)\n",
"\n",
"print(\"La barrière a été franchie\" if is_barrier_breached(X, B) else \"La barrière n'a pas été franchie\")"
"\n",
"print(\n",
" \"La barrière a été franchie\"\n",
" if is_barrier_breached(X, B)\n",
" else \"La barrière n'a pas été franchie\"\n",
")"
]
},
{
@@ -299,18 +309,19 @@
" trajectories (list of tuples): Liste des trajectoires avec le temps et les valeurs\n",
" B (float): Valeur de la barrière\n",
" \"\"\"\n",
" for (t, X) in trajectories:\n",
" col = 'pink' if is_barrier_breached(X, B) else 'lime'\n",
" for t, X in trajectories:\n",
" col = \"pink\" if is_barrier_breached(X, B) else \"lime\"\n",
" plt.plot(t, X, alpha=0.5, color=col)\n",
" plt.title('Simulation d\\'Euler-Maruyama pour une EDS')\n",
" \n",
" plt.axhline(B, label='Barrière', color='red', linestyle='--')\n",
" \n",
" plt.title(\"Simulation d'Euler-Maruyama pour une EDS\")\n",
"\n",
" plt.axhline(B, label=\"Barrière\", color=\"red\", linestyle=\"--\")\n",
"\n",
" plt.legend()\n",
" plt.xlabel('Temps')\n",
" plt.ylabel('X(t)')\n",
" plt.xlabel(\"Temps\")\n",
" plt.ylabel(\"X(t)\")\n",
" plt.grid()\n",
" \n",
"\n",
"\n",
"def payoff(X, B, K):\n",
" \"\"\"Calcule le payoff d'une option en fonction des trajectoires.\n",
"\n",
@@ -324,9 +335,10 @@
" \"\"\"\n",
" if not is_barrier_breached(X, B):\n",
" return max(X[-1] - K, 0)\n",
" else: \n",
" else:\n",
" return 0\n",
" \n",
"\n",
"\n",
"def call_BS(x):\n",
" \"\"\"Calcul du prix d'une option d'achat européenne selon le modèle de Black-Scholes en fonction de x.\n",
"\n",
@@ -336,27 +348,34 @@
" Retourne:\n",
" float: Le prix de l'option d'achat européenne.\n",
" \"\"\"\n",
" d1 = (np.log(x/K) + (r + 0.5 * sigma**2) * T) / (sigma * np.sqrt(T))\n",
" d1 = (np.log(x / K) + (r + 0.5 * sigma**2) * T) / (sigma * np.sqrt(T))\n",
" d2 = d1 - sigma * np.sqrt(T)\n",
" return x * stats.norm.cdf(d1) - K * np.exp(-r * T) * stats.norm.cdf(d2)\n",
" \n",
"\n",
"\n",
"def compute_payoff_BS():\n",
" \"\"\"Calcul du prix d'une option d'achat Up-and-Out selon le modèle de Black-Scholes en fonction de la barrière.\n",
" \n",
"\n",
" Retourne:\n",
" float: Le prix de l'option d'achat Up-and-Out.\n",
" \"\"\"\n",
" lam = (r + 0.5 * sigma**2) / sigma**2\n",
" return call_BS(S0) - call_BS(S0) * (S0/B)**(2 * lam) + (S0/B)**(lam - 1) * (call_BS(B**2/S0) - (S0/B)**2 * call_BS(B**2/S0))\n",
" \n",
" return (\n",
" call_BS(S0)\n",
" - call_BS(S0) * (S0 / B) ** (2 * lam)\n",
" + (S0 / B) ** (lam - 1)\n",
" * (call_BS(B**2 / S0) - (S0 / B) ** 2 * call_BS(B**2 / S0))\n",
" )\n",
"\n",
"\n",
"def compute_payoff(trajectories, B, K):\n",
" \"\"\"Calcule le payoff d'une option en fonction des trajectoires.\n",
" \n",
"\n",
" Paramètres:\n",
" trajectories (list of tuples): Liste des trajectoires avec le temps et les valeurs.\n",
" B (float): Valeur de la barrière.\n",
" K (float): Prix d'exercice de l'option.\n",
" \n",
"\n",
" Retourne:\n",
" float: Valeur du payoff de l'option.\n",
" \"\"\"\n",
@@ -390,7 +409,13 @@
],
"source": [
"N_trajectories = 1000\n",
"trajectories = [(t, X) for (t, X) in [euler_maruyama(mu=r, sigma=sigma, T=T, N=1000, X0=S0) for _ in range(N_trajectories)]]\n",
"trajectories = [\n",
" (t, X)\n",
" for (t, X) in [\n",
" euler_maruyama(mu=r, sigma=sigma, T=T, N=1000, X0=S0)\n",
" for _ in range(N_trajectories)\n",
" ]\n",
"]\n",
"plt.figure(figsize=(10, 6))\n",
"plot_browniens(trajectories, B=B)\n",
"plt.show()\n",
@@ -431,28 +456,35 @@
"\n",
"np.random.seed(333)\n",
"\n",
"\n",
"def plot_payoff_errors():\n",
" \"\"\"Trace l'erreur de convergence du payoff actualisé en fonction de N.\"\"\"\n",
" errors = []\n",
" \n",
"\n",
" for N in N_list:\n",
" trajectories = [(t, X) for (t, X) in [euler_maruyama(mu=r, sigma=sigma, T=T, N=N, X0=S0) for _ in range(N_trajectories)]]\n",
" trajectories = [\n",
" (t, X)\n",
" for (t, X) in [\n",
" euler_maruyama(mu=r, sigma=sigma, T=T, N=N, X0=S0)\n",
" for _ in range(N_trajectories)\n",
" ]\n",
" ]\n",
" payoff_BS = compute_payoff_BS()\n",
" payoffs = compute_payoff(trajectories, B, K)\n",
" \n",
"\n",
" errors.append(np.max(np.abs(payoffs - payoff_BS)))\n",
" \n",
" \n",
" plt.plot(np.log(N_list), np.log(errors), 'o-', label='Erreur numérique')\n",
" plt.plot(np.log(N_list), 0.5 * np.log(N_list), '--', label='Ordre 1/2')\n",
" plt.plot(np.log(N_list), np.log(N_list), '--', label='Ordre 1')\n",
" plt.plot(np.log(N_list), 2*np.log(N_list), '--', label='Ordre 2')\n",
" plt.xlabel('log(h)')\n",
" plt.ylabel('log(Erreur)')\n",
" plt.title('Convergence de l\\'erreur du payoff actualisé')\n",
"\n",
" plt.plot(np.log(N_list), np.log(errors), \"o-\", label=\"Erreur numérique\")\n",
" plt.plot(np.log(N_list), 0.5 * np.log(N_list), \"--\", label=\"Ordre 1/2\")\n",
" plt.plot(np.log(N_list), np.log(N_list), \"--\", label=\"Ordre 1\")\n",
" plt.plot(np.log(N_list), 2 * np.log(N_list), \"--\", label=\"Ordre 2\")\n",
" plt.xlabel(\"log(h)\")\n",
" plt.ylabel(\"log(Erreur)\")\n",
" plt.title(\"Convergence de l'erreur du payoff actualisé\")\n",
" plt.legend()\n",
" plt.grid(True)\n",
"\n",
"\n",
"plt.figure(figsize=(10, 5))\n",
"plot_payoff_errors()\n",
"plt.show()"

View File

@@ -28,8 +28,9 @@
"k = np.arange(1, 12 + 1)\n",
"m = np.power(2, k)\n",
"\n",
"\n",
"def f(x):\n",
"\treturn 1 / np.sqrt(x)"
" return 1 / np.sqrt(x)"
]
},
{
@@ -39,19 +40,23 @@
"outputs": [],
"source": [
"a, b = 1, 2\n",
"\n",
"\n",
"def compute_I(f, a, b, m):\n",
" h_list = (b - a) / m\n",
" I = []\n",
" errors = []\n",
" sol_exact = quad(f, a, b)[0]\n",
" \n",
"\n",
" for h in h_list:\n",
" t = np.arange(a, b, h)\n",
" y = np.array([3/4 * h * f(t[i] + h/3) + h/4 * f(t[i] + h) for i in range(len(t))])\n",
" y = np.array(\n",
" [3 / 4 * h * f(t[i] + h / 3) + h / 4 * f(t[i] + h) for i in range(len(t))]\n",
" )\n",
" I_approx = np.sum(y)\n",
" I.append(I_approx)\n",
" errors.append(np.abs(I_approx - sol_exact))\n",
" \n",
"\n",
" return I, h_list, errors"
]
},
@@ -84,12 +89,12 @@
"print(f\"I1 = {I1}\")\n",
"\n",
"plt.figure(figsize=(10, 5))\n",
"plt.plot(np.log(h_list), np.log(errors1), 'o-', label='Erreur numérique')\n",
"plt.plot(np.log(h_list), 2*np.log(h_list), '--', label='Ordre 2')\n",
"plt.plot(np.log(h_list), 4*np.log(h_list), '--', label='Ordre 4')\n",
"plt.xlabel('log(h)')\n",
"plt.ylabel('log(Erreur)')\n",
"plt.title('Convergence de la méthode d\\'intégration')\n",
"plt.plot(np.log(h_list), np.log(errors1), \"o-\", label=\"Erreur numérique\")\n",
"plt.plot(np.log(h_list), 2 * np.log(h_list), \"--\", label=\"Ordre 2\")\n",
"plt.plot(np.log(h_list), 4 * np.log(h_list), \"--\", label=\"Ordre 4\")\n",
"plt.xlabel(\"log(h)\")\n",
"plt.ylabel(\"log(Erreur)\")\n",
"plt.title(\"Convergence de la méthode d'intégration\")\n",
"plt.legend()\n",
"plt.grid(True)\n",
"plt.show()"
@@ -116,12 +121,12 @@
"I2, h_list, errors2 = compute_I(f, a, b, m)\n",
"\n",
"plt.figure(figsize=(10, 5))\n",
"plt.plot(np.log(h_list), np.log(errors2), label='Approximation de l\\'intégrale')\n",
"plt.plot(np.log(h_list), np.log(h_list), '--', label='h')\n",
"plt.plot(np.log(h_list), 2*np.log(h_list), '--', label='h^2')\n",
"plt.xlabel('h')\n",
"plt.ylabel('Approximation de l\\'intégrale')\n",
"plt.title('Approximation de l\\'intégrale par la méthode de Simpson')\n",
"plt.plot(np.log(h_list), np.log(errors2), label=\"Approximation de l'intégrale\")\n",
"plt.plot(np.log(h_list), np.log(h_list), \"--\", label=\"h\")\n",
"plt.plot(np.log(h_list), 2 * np.log(h_list), \"--\", label=\"h^2\")\n",
"plt.xlabel(\"h\")\n",
"plt.ylabel(\"Approximation de l'intégrale\")\n",
"plt.title(\"Approximation de l'intégrale par la méthode de Simpson\")\n",
"plt.legend()\n",
"plt.show()"
]
@@ -146,19 +151,19 @@
"metadata": {},
"outputs": [],
"source": [
"def RKI(f, y0, vt, tol = 1e-6, itmax = 20):\n",
"\tN, T = len(vt), vt[-1]\n",
"\tyn = np.zeros((len(y0), N))\n",
"\tyn[:, 0] = y0\n",
"\th = T / N\n",
"def RKI(f, y0, vt, tol=1e-6, itmax=20):\n",
" N, T = len(vt), vt[-1]\n",
" yn = np.zeros((len(y0), N))\n",
" yn[:, 0] = y0\n",
" h = T / N\n",
"\n",
"\tfor n in range(N-1):\n",
"\t\tp1 = f(vt[n], yn[:, n])\n",
"\t\tF1 = lambda p2: f(vt[n] + h/3, yn[:, n] + h/6 * (p1 + p2)) - p2\n",
"\t\tp2 = newton(F1, yn[:, n], fprime=None, tol=tol, maxiter=itmax)\n",
"\t\tF2 = lambda yn1: yn[:, n] + h/4 * (3 * p2 + f(vt[n+1], yn1)) - yn1\n",
"\t\tyn[:, n + 1] = newton(F2, yn[:, n], fprime=None, tol=tol, maxiter=itmax)\n",
"\treturn yn"
" for n in range(N - 1):\n",
" p1 = f(vt[n], yn[:, n])\n",
" F1 = lambda p2: f(vt[n] + h / 3, yn[:, n] + h / 6 * (p1 + p2)) - p2\n",
" p2 = newton(F1, yn[:, n], fprime=None, tol=tol, maxiter=itmax)\n",
" F2 = lambda yn1: yn[:, n] + h / 4 * (3 * p2 + f(vt[n + 1], yn1)) - yn1\n",
" yn[:, n + 1] = newton(F2, yn[:, n], fprime=None, tol=tol, maxiter=itmax)\n",
" return yn"
]
},
{
@@ -194,14 +199,18 @@
"source": [
"a, b = [0, 2]\n",
"\n",
"\n",
"def f(t, y):\n",
" return t * np.power(y, 3) - t * y\n",
" \n",
"\n",
"\n",
"y0 = [0.5]\n",
"\n",
"\n",
"def sol_exact(t):\n",
" return 1 / np.sqrt(1 + 3 * np.exp(np.power(t, 2)))\n",
"\n",
"\n",
"x_fine = np.linspace(a, b, 1000)\n",
"y_fine = sol_exact(x_fine)\n",
"\n",
@@ -212,13 +221,13 @@
"y_exact_interp = np.interp(vt, x_fine, y_fine)\n",
"\n",
"plt.figure(figsize=(10, 5))\n",
"plt.plot(x_fine, y_fine, label='Solution exacte')\n",
"plt.scatter(vt, y, label='Solution numérique', color='red')\n",
"plt.plot(x_fine, y_fine, label=\"Solution exacte\")\n",
"plt.scatter(vt, y, label=\"Solution numérique\", color=\"red\")\n",
"plt.legend()\n",
"plt.show()\n",
"\n",
"error = np.max(np.abs(y - y_exact_interp))\n",
"print(f\"Error with h={h}: {error}\")\n"
"print(f\"Error with h={h}: {error}\")"
]
},
{
@@ -246,7 +255,7 @@
],
"source": [
"k = np.arange(1, 10 + 1)\n",
"h_list = 1/np.power(2, k)\n",
"h_list = 1 / np.power(2, k)\n",
"\n",
"errors = []\n",
"for h in h_list:\n",
@@ -258,14 +267,14 @@
"log_h = np.log(h_list)\n",
"log_errors = np.log(errors)\n",
"order = np.polyfit(log_h, log_errors, 1)[0]\n",
" \n",
"\n",
"plt.figure(figsize=(10, 5))\n",
"plt.plot(log_h, log_errors, 'o-', label=f'Erreur (ordre {order:.2f})')\n",
"plt.plot(log_h, log_h, '--', label='h')\n",
"plt.plot(log_h, 2*log_h, '--', label='h^2')\n",
"plt.plot(log_h, 4*log_h, '--', label='h^4')\n",
"plt.xlabel('log(h)')\n",
"plt.ylabel('log(error)')\n",
"plt.plot(log_h, log_errors, \"o-\", label=f\"Erreur (ordre {order:.2f})\")\n",
"plt.plot(log_h, log_h, \"--\", label=\"h\")\n",
"plt.plot(log_h, 2 * log_h, \"--\", label=\"h^2\")\n",
"plt.plot(log_h, 4 * log_h, \"--\", label=\"h^4\")\n",
"plt.xlabel(\"log(h)\")\n",
"plt.ylabel(\"log(error)\")\n",
"plt.legend()\n",
"plt.grid(True)\n",
"plt.show()\n",
@@ -306,11 +315,14 @@
"source": [
"def F(t, Y):\n",
" x, y, z = Y\n",
" return np.array([\n",
" 1 + np.power(x, 2) * y - (z + 1) * x,\n",
" x * z - np.power(x, 2) * y,\n",
" - x * z + 1.45\n",
" ])\n",
" return np.array(\n",
" [\n",
" 1 + np.power(x, 2) * y - (z + 1) * x,\n",
" x * z - np.power(x, 2) * y,\n",
" -x * z + 1.45,\n",
" ]\n",
" )\n",
"\n",
"\n",
"h = 0.025\n",
"y0 = np.array([1, 1, 1])\n",
@@ -320,20 +332,20 @@
"y = RKI(F, y0, t)\n",
"fig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(15, 5))\n",
"\n",
"ax1.scatter(y[0], y[1], label='Solution numérique', color='red')\n",
"ax1.plot(sol_exact[:, 0], sol_exact[:, 1], label='Solution exacte', color='blue')\n",
"ax1.scatter(y[0], y[1], label=\"Solution numérique\", color=\"red\")\n",
"ax1.plot(sol_exact[:, 0], sol_exact[:, 1], label=\"Solution exacte\", color=\"blue\")\n",
"ax1.legend()\n",
"ax1.set_title('x vs y')\n",
"ax1.set_title(\"x vs y\")\n",
"\n",
"ax2.scatter(y[1], y[2], label='Solution numérique', color='red')\n",
"ax2.plot(sol_exact[:, 1], sol_exact[:, 2], label='Solution exacte', color='blue')\n",
"ax2.scatter(y[1], y[2], label=\"Solution numérique\", color=\"red\")\n",
"ax2.plot(sol_exact[:, 1], sol_exact[:, 2], label=\"Solution exacte\", color=\"blue\")\n",
"ax2.legend()\n",
"ax2.set_title('y vs z')\n",
"ax2.set_title(\"y vs z\")\n",
"\n",
"ax3.scatter(y[0], y[2], label='Solution numérique', color='red')\n",
"ax3.plot(sol_exact[:, 0], sol_exact[:, 2], label='Solution exacte', color='blue')\n",
"ax3.scatter(y[0], y[2], label=\"Solution numérique\", color=\"red\")\n",
"ax3.plot(sol_exact[:, 0], sol_exact[:, 2], label=\"Solution exacte\", color=\"blue\")\n",
"ax3.legend()\n",
"ax3.set_title('x vs z')\n",
"ax3.set_title(\"x vs z\")\n",
"\n",
"plt.tight_layout()\n",
"plt.show()"
@@ -357,14 +369,15 @@
],
"source": [
"def R(z):\n",
" return (1 + 3/4 * z * (1 + z/6)/(1 - z/6)) / (1 - z/4)\n",
" return (1 + 3 / 4 * z * (1 + z / 6) / (1 - z / 6)) / (1 - z / 4)\n",
"\n",
"\n",
"x = np.linspace(-15, 5, 100)\n",
"y = np.linspace(-7.5, 7.5, 100)\n",
"X, Y = np.meshgrid(x, y)\n",
"Z = R(X + 1j*Y)\n",
"Z = R(X + 1j * Y)\n",
"plt.figure(figsize=(10, 7))\n",
"plt.contour(X, Y, np.abs(Z), levels=[1], cmap='rainbow')\n",
"plt.contour(X, Y, np.abs(Z), levels=[1], cmap=\"rainbow\")\n",
"plt.grid()\n",
"plt.show()"
]