0% found this document useful (0 votes)
5 views9 pages

Code2pdf 681f54ff2111c

The document contains Python code implementing the Runge-Kutta method for solving ordinary differential equations (ODEs). Various examples demonstrate the application of this method to different differential equations, including dy/dx = f(x, y) with specific initial conditions. The output of each example provides the computed value of y at a specified x value.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views9 pages

Code2pdf 681f54ff2111c

The document contains Python code implementing the Runge-Kutta method for solving ordinary differential equations (ODEs). Various examples demonstrate the application of this method to different differential equations, including dy/dx = f(x, y) with specific initial conditions. The output of each example provides the computed value of y at a specified x value.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

{

"cells": [
{
"cell_type": "code",
"execution_count": 2,
"id": "d671bd8d-9147-43f5-a2df-d4fe0392c618",
"metadata": {},
"outputs": [],
"source": [
"import numpy as np\n",
"import matplotlib.pyplot as plt\n",
"\n",
"def f(x, y):\n",
" \"\"\"Example function dy/dx = f(x, y)\"\"\"\n",
" return x + y\n",
"\n",
"def runge_kutta(x0, y0, x_end, h):\n",
" \n",
" n = int((x_end - x0) / h) # Number of steps\n",
" x = np.lin[space(x0, x_end, n+1)]\n",
" y = np.zeros(n+1)\n",
" \n",
" y[0] = y0\n",
" \n",
" for i in range(n):\n",
" k1 = h * f(x[i], y[i])\n",
" k2 = h * f(x[i] + h/2, y[i] + k1/2)\n",
" k3 = h * f(x[i] + h/2, y[i] + k2/2)\n",
" k4 = h * f(x[i] + h, y[i] + k3)\n",
" \n",
" y[i+1] = y[i] + (k1 + 2*k2 + 2*k3 + k4) / 6\n",
" \n",
" return x, y\n",
"\n",
"\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "badb7194-142d-40f4-b414-e9e117e01d86",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"y(1.05) = 1.332557\n"
]
}
],
"source": [
"#ex. dy/dx=x**2+y**2\n",
"import numpy as np\n",
"\n",
"def rk4_single_step(f, x, y, h):\n",
" \"\"\"Computes one step of the RK4 method.\"\"\"\n",
" k1 = h * f(x, y)\n",
" k2 = h * f(x + h / 2, y + k1 / 2)\n",
" k3 = h * f(x + h / 2, y + k2 / 2)\n",
" k4 = h * f(x + h, y + k3)\n",
" return y + (k1 + 2*k2 + 2*k3 + k4) / 6\n",
"\n",
"# Given differential equation\n",
"def f(x, y):\n",
" return x**2 + y**2\n",
"\n",
"# Initial conditions\n",
"x0, y0 = 1, 1.2\n",
"h = 0.05\n",
"x_target = 1.05\n",
"\n",
"# Compute y at x=1.05\n",
"y_target = rk4_single_step(f, x0, y0, h)\n",
"\n",
"print(f\"y({x_target}) = {y_target:.6f}\")\n",
".\n"
]
},
{
"cell_type": "code",
"execution_count": 17,
"id": "ab193a74-20eb-4bfd-81c9-97e16172cb3d",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"y(1.05) = 0.818733\n"
]
}
],
"source": [
"#ex. dy/dx=-2*y\n",
"import numpy as np\n",
"\n",
"def rk4_single_step(f, x, y, h):\n",
" \"\"\"Computes one step of the RK4 method.\"\"\"\n",
" k1 = h * f(x, y)\n",
" k2 = h * f(x + h / 2, y + k1 / 2)\n",
" k3 = h * f(x + h / 2, y + k2 / 2)\n",
" k4 = h * f(x + h, y + k3)\n",
" return y + (k1 + 2*k2 + 2*k3 + k4) / 6\n",
"\n",
"# Given differential equation\n",
"def f(x, y):\n",
" return -2*y\n",
"\n",
"# Initial conditions\n",
"x0, y0 = 0, 1\n",
"h = 0.1\n",
"x_target = 1.05\n",
"\n",
"# Compute y at x=1\n",
"y_target = rk4_single_step(f, x0, y0, h)\n",
"\n",
"print(f\"y({x_target}) = {y_target:.6f}\")"
]
},
{
"cell_type": "code",
"execution_count": 8,
"id": "047a5d4d-71ec-43df-b8e3-8ac3499d5d08",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"y(1.05) = 0.953688\n"
]
}
],
"source": [
"#ex. dy/dx=(x-y)/2\n",
"import numpy as np\n",
"\n",
"def rk4_single_step(f, x, y, h):\n",
" \"\"\"Computes one step of the RK4 method.\"\"\"\n",
" k1 = h * f(x, y)\n",
" k2 = h * f(x + h / 2, y + k1 / 2)\n",
" k3 = h * f(x + h / 2, y + k2 / 2)\n",
" k4 = h * f(x + h, y + k3)\n",
" return y + (k1 + 2*k2 + 2*k3 + k4) / 6\n",
"\n",
"# Given differential equation\n",
"def f(x, y):\n",
" return (x-y)/2\n",
"\n",
"# Initial conditions\n",
"x0, y0 = 0, 1\n",
"h = 0.1\n",
"x_target = 1.05\n",
"\n",
"# Compute y at x=1\n",
"y_target = rk4_single_step(f, x0, y0, h)\n",
"\n",
"print(f\"y({x_target}) = {y_target:.6f}\")"
]
},
{
"cell_type": "code",
"execution_count": 6,
"id": "2c91904a-a16b-44f9-bd37-85b1611082f4",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"y(1.05) = 0.836426\n"
]
}
],
"source": [
"#ex. dy/dx=(x-y)/2\n",
"import numpy as np\n",
"\n",
"def rk4_single_step(f, x, y, h):\n",
" \"\"\"Computes one step of the RK4 method.\"\"\"\n",
" k1 = h * f(x, y)\n",
" k2 = h * f(x + h / 2, y + k1 / 2)\n",
" k3 = h * f(x + h / 2, y + k2 / 2)\n",
" k4 = h * f(x + h, y + k3)\n",
" return y + (k1 + 2*k2 + 2*k3 + k4) / 6\n",
"\n",
"# Given differential equation\n",
"def f(x, y):\n",
" return (x-y)/2\n",
"\n",
"# Initial conditions\n",
"x0, y0 = 0, 1\n",
"h = 0.5\n",
"x_1 = 1.05\n",
"\n",
"# Compute y at x=1\n",
"y_1 = rk4_single_step(f, x0, y0, h)\n",
"\n",
"print(f\"y({x_1}) = {y_1:.6f}\")"
]
},
{
"cell_type": "code",
"execution_count": 5,
"id": "855f2688-c602-422c-9854-56ec7af51511",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"y(1.2) = 2.475605\n"
]
}
],
"source": [
"#ex. dy/dx=math.sin(x*y)-x**2*y\n",
"import math\n",
"def rk4(f, x, y, h):\n",
" k1 = h * f(x, y)\n",
" k2 = h * f(x + h / 2, y + k1 / 2)\n",
" k3 = h * f(x + h / 2, y + k2 / 2)\n",
" k4 = h * f(x + h, y + k3)\n",
" return y + (k1 + 2*k2 + 2*k3 + k4) / 6\n",
"def f(x, y):\n",
" return math.sin(x*y)-x**2*y\n",
"x0, y0 = 1, math.pi\n",
"h = 0.2\n",
"x1 = 1.2\n",
"y1 = rk4(f, x0, y0, h)\n",
"print(f\"y({x1}) = {y1:.6f}\")"
]
},
{
"cell_type": "code",
"execution_count": 6,
"id": "4117f935-068a-4fe2-abbc-1646231f27fa",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"y(1.1) = 2.961316\n"
]
}
],
"source": [
"#ex. dy/dx=(1+x)/(1-y**2)\n",
"import math\n",
"\n",
"def rk4_single_step(f, x, y, h):\n",
" \"\"\"Computes one step of the RK4 method.\"\"\"\n",
" k1 = h * f(x, y)\n",
" k2 = h * f(x + h / 2, y + k1 / 2)\n",
" k3 = h * f(x + h / 2, y + k2 / 2)\n",
" k4 = h * f(x + h, y + k3)\n",
" return y + (k1 + 2*k2 + 2*k3 + k4) / 6\n",
"\n",
"# Given differential equation\n",
"def f(x, y):\n",
" return (1+x)/(1-y**2)\n",
"# Initial conditions\n",
"x0, y0 = 2, 3\n",
"h = 0.1\n",
"x_1 = 1.1\n",
"\n",
"# Compute y at x=1\n",
"y_1 = rk4_single_step(f, x0, y0, h)\n",
"\n",
"print(f\"y({x_1}) = {y_1:.6f}\")"
]
},
{
"cell_type": "code",
"execution_count": 8,
"id": "2142770a-1838-4249-9acf-78d1e96bc570",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"y(1.1) = 1.221551\n"
]
}
],
"source": [
"#ex. dy/dx=y+np.sqrt(x**2+y**2)\n",
"import numpy as np\n",
"\n",
"def rk4_single_step(f, x, y, h):\n",
" \"\"\"Computes one step of the RK4 method.\"\"\"\n",
" k1 = h * f(x, y)\n",
" k2 = h * f(x + h / 2, y + k1 / 2)\n",
" k3 = h * f(x + h / 2, y + k2 / 2)\n",
" k4 = h * f(x + h, y + k3)\n",
" return y + (k1 + 2*k2 + 2*k3 + k4) / 6\n",
"\n",
"# Given differential equation\n",
"def f(x, y):\n",
" return y+np.sqrt(x**2+y**2)\n",
"# Initial conditions\n",
"x0, y0 = 0, 1\n",
"h = 0.1\n",
"x_1 = 1.1\n",
"\n",
"# Compute y at x=1\n",
"y_1 = rk4_single_step(f, x0, y0, h)\n",
"\n",
"print(f\"y({x_1}) = {y_1:.6f}\")"
]
},
{
"cell_type": "code",
"execution_count": 1,
"id": "81f97da4-f65e-4dd5-b902-b1f815ab95f9",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"y(0.2) ≈ 1.0936686601837953\n"
]
}
],
"source": [
"#ex1. #date 11 april\n",
"def f(t, y):\n",
" return 0.5 * y * (1 - y / 10)\n",
"\n",
"t0 = 0\n",
"y0 = 1\n",
"h = 0.2\n",
"\n",
"k1 = h * f(t0, y0)\n",
"k2 = h * f(t0 + h/2, y0 + k1/2)\n",
"k3 = h * f(t0 + h/2, y0 + k2/2)\n",
"k4 = h * f(t0 + h, y0 + k3)\n",
"\n",
"y1 = y0 + (k1 + 2*k2 + 2*k3 + k4) / 6\n",
"\n",
"print(f\"y(0.2) ≈ {y1}\")"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "7bb0e8ad-65b2-4924-ba5b-d437f7a74632",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"T(0.2) ≈ 89.0268 °C\n"
]
}
],
"source": [
"def dT_dt(t, T, Ta=20, k=0.07):\n",
" return -k * (T - Ta)\n",
"\n",
"t0 = 0\n",
"T0 = 90\n",
"h = 0.2\n",
"\n",
"k1 = h * dT_dt(t0, T0)\n",
"k2 = h * dT_dt(t0 + h/2, T0 + k1/2)\n",
"k3 = h * dT_dt(t0 + h/2, T0 + k2/2)\n",
"k4 = h * dT_dt(t0 + h, T0 + k3)\n",
"\n",
"T1 = T0 + (k1 + 2*k2 + 2*k3 + k4) / 6\n",
"\n",
"print(f\"T(0.2) ≈ {T1:.4f} °C\")"
]
},
{
"cell_type": "code",
"execution_count": 9,
"id": "6838a483-7676-4934-8ace-e12224aab3e3",
"metadata": {},
"outputs": [
{
"ename": "OverflowError",
"evalue": "(34, 'Result too large')",
"output_type": "error",
"traceback": [
"\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[1;31mOverflowError\u001b[0m Traceback (most recent call last)",
"Cell \u001b[1;32mIn[9], line 32\u001b[0m\n\u001b[0;32m 30\u001b[0m plt\u001b[38;5;241m.\u001b[39mfigure(figsize\u001b[38;5;241m=\u001b[39m(\u001b[38;5;241m8
"Cell \u001b[1;32mIn[9], line 14\u001b[0m, in \u001b[0;36mrk4\u001b[1;34m(x0, t0, tf, h)\u001b[0m\n\u001b[0;32m 12\u001b[0m x \u001b[38;5;241m=\u001b[39m x0
"Cell \u001b[1;32mIn[9], line 6\u001b[0m, in \u001b[0;36mf\u001b[1;34m(x)\u001b[0m\n\u001b[0;32m 5\u001b[0m \u001b[38;5;28;01mdef\u001b[39;00m\u001b[38;5;250m
"\u001b[1;31mOverflowError\u001b[0m: (34, 'Result too large')"
]
},
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAp4AAAGsCAYAAAB0LKeoAAAAOnRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjEwLjAsIGh0dHBzOi8vbWF0cGxvdGxpYi5vcmcvlHJYcgAAAAlwSFlzAA
"text/plain": [
"<Figure size 800x500 with 1 Axes>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"# dx/dt=x**2-3 plot the trajectory of the system i.e. x vs t\n",
"import numpy as np\n",
"import matplotlib.pyplot as plt\n",
"\n",
"def f(x):\n",
" return x**2 - 3\n",
"\n",
"def rk4(x0, t0, tf, h):\n",
" t_values = [t0]\n",
" x_values = [x0]\n",
" t = t0\n",
" x = x0\n",
" while t < tf:\n",
" k1 = h * f(x)\n",
" k2 = h * f(x + 0.5 * k1)\n",
" k3 = h * f(x + 0.5 * k2)\n",
" k4 = h * f(x + k3)\n",
" x += (k1 + 2*k2 + 2*k3 + k4) / 6\n",
" t += h\n",
" t_values.append(t)\n",
" x_values.append(x)\n",
" return t_values, x_values\n",
"\n",
"t0 = 0.0\n",
"tf = 5.0\n",
"h = 0.01\n",
"initial_conditions = [-3, -np.sqrt(3), 0, np.sqrt(3), 3]\n",
"\n",
"\n",
"plt.figure(figsize=(8,5))\n",
"for x0 in initial_conditions:\n",
" t_vals, x_vals = rk4(x0, t0, tf, h)\n",
" plt.plot(t_vals, x_vals, label=f'x₀ = {x0:.2f}')\n",
"\n",
"plt.xlabel('Time t')\n",
"plt.ylabel('x(t)')\n",
"plt.title('Trajectories of dx/dt = x² - 3 for Various Initial Conditions')\n",
"plt.grid(True)\n",
"plt.legend()\n",
"plt.show()\n"
]
},
{
"cell_type": "code",
"execution_count": 15,
"id": "ccfc1340-cf40-4476-b152-f519c40c0cd0",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Final temperature at t=480 with h=120: 642.28 K\n",
"Final temperature at t=480 with h=240: 590.68 K\n",
"Final temperature at t=480 with h=480: -73.59 K\n"
]
},
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAjoAAAGdCAYAAAAbudkLAAAAOnRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjEwLjAsIGh0dHBzOi8vbWF0cGxvdGxpYi5vcmcvlHJYcgAAAAlwSFlzAA
"text/plain": [
"<Figure size 640x480 with 1 Axes>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"import matplotlib.pyplot as plt\n",
"\n",
"def f(theta):\n",
" return -2.2067e-12 * (theta**4 - 8.1e8)\n",
"\n",
"def rk4(theta, h):\n",
" t = 0\n",
" T = [theta]\n",
" time = [t]\n",
" while t < 480:\n",
" k1 = h * f(theta)\n",
" k2 = h * f(theta + k1/2)\n",
" k3 = h * f(theta + k2/2)\n",
" k4 = h * f(theta + k3)\n",
" theta += (k1 + 2*k2 + 2*k3 + k4) / 6\n",
" t += h\n",
" T.append(theta)\n",
" time.append(t)\n",
" return time, T\n",
"\n",
"steps = [120, 240, 480]\n",
"\n",
"for h in steps:\n",
" t, temp = rk4(1200, h)\n",
" plt.plot(t, temp, label=f'h = {h}')\n",
" print(f\"Final temperature at t=480 with h={h}: {temp[-1]:.2f} K\")\n",
"\n",
"\n",
"plt.grid()\n",
"plt.show()\n"
]
},
{
"cell_type": "code",
"execution_count": 1,
"id": "050a74ab-b260-4812-9ed3-0a15c3e01091",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"After step 1: t = 120 s, θ = 895.7448 K\n",
"After step 2: t = 240 s, θ = 772.1379 K\n",
"After step 3: t = 360 s, θ = 697.7158 K\n",
"After step 4: t = 480 s, θ = 646.1608 K\n",
"\n",
"Temperature at t = 480 s: θ = 646.1608 K\n"
]
}
],
"source": [
"def f(theta):\n",
" \"\"\"Differential equation for radiative cooling\"\"\"\n",
" return -2.2067e-12 * (theta**4 - 81e8)\n",
"\n",
"def rk4(theta0, t0, h, steps):\n",
" \"\"\"Runge-Kutta 4th Order Method implementation\"\"\"\n",
" theta = theta0\n",
" t = t0\n",
" for i in range(steps):\n",
" k1 = h * f(theta)\n",
" k2 = h * f(theta + 0.5 * k1)\n",
" k3 = h * f(theta + 0.5 * k2)\n",
" k4 = h * f(theta + k3)\n",
" theta += (1/6) * (k1 + 2*k2 + 2*k3 + k4)\n",
" t += h\n",
" print(f\"After step {i+1}: t = {t} s, θ = {theta:.4f} K\")\n",
" return theta\n",
"\n",
"# Initial conditions\n",
"theta0 = 1200 # K\n",
"t0 = 0 # seconds\n",
"h = 120 # step size\n",
"steps = 4 # because 480 / 120 = 4\n",
"\n",
"# Solve using RK4\n",
"final_temperature = rk4(theta0, t0, h, steps)\n",
"\n",
"print(f\"\\nTemperature at t = 480 s: θ = {final_temperature:.4f} K\")\n"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "7ede24e1-7c56-4a5c-b5ef-3354c30623eb",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Temperature at t = 480 s: θ = 646.1608 K\n"
]
},
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAxUAAAHqCAYAAAByRmPvAAAAOnRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjEwLjAsIGh0dHBzOi8vbWF0cGxvdGxpYi5vcmcvlHJYcgAAAAlwSFlzAA
"text/plain": [
"<Figure size 800x500 with 1 Axes>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"import numpy as np\n",
"import matplotlib.pyplot as plt\n",
"def f(theta):\n",
" return -2.2067e-12 * (theta**4 - 81e8)\n",
"def rk4(theta0, t0, h, steps):\n",
" theta = theta0\n",
" t = t0\n",
" time_values = [t]\n",
" theta_values = [theta]\n",
"\n",
" for i in range(steps):\n",
" k1 = h * f(theta)\n",
" k2 = h * f(theta + 0.5 * k1)\n",
" k3 = h * f(theta + 0.5 * k2)\n",
" k4 = h * f(theta + k3)\n",
" theta += (1/6) * (k1 + 2*k2 + 2*k3 + k4)\n",
" t += h\n",
" time_values.append(t)\n",
" theta_values.append(theta)\n",
"\n",
" return time_values, theta_values\n",
"theta0 = 1200 # Initial temperature in Kelvin\n",
"t0 = 0 # Initial time in seconds\n",
"h = 120 # Step size in seconds\n",
"steps = 4 # Number of steps to reach 480 seconds\n",
"\n",
"time_values, theta_values = rk4(theta0, t0, h, steps)\n",
"\n",
"print(f\"Temperature at t = 480 s: θ = {theta_values[-1]:.4f} K\")\n",
"\n",
"plt.figure(figsize=(8, 5))\n",
"plt.plot(time_values, theta_values, marker='o', linestyle='-', color='b')\n",
"plt.title(\"Temperature vs Time using RK4 Method\")\n",
"plt.xlabel(\"Time (seconds)\")\n",
"plt.ylabel(\"Temperature (K)\")\n",
"plt.grid(True)\n",
"plt.tight_layout()\n",
"plt.show()"
]
},
{
"cell_type": "code",
"execution_count": 5,
"id": "094a1115-07a3-40e7-a0cc-543437520f2c",
"metadata": {},
"outputs": [
{
"ename": "NameError",
"evalue": "name 'i' is not defined",
"output_type": "error",
"traceback": [
"\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[1;31mNameError\u001b[0m Traceback (most recent call last)",
"Cell \u001b[1;32mIn[5], line 18\u001b[0m\n\u001b[0;32m 16\u001b[0m values\u001b[38;5;241m.\u001b[39mappend(theta)\n\u001b[0;32m 17\u001b[0m
"\u001b[1;31mNameError\u001b[0m: name 'i' is not defined"
]
}
],
"source": [
"import numpy as np\n",
"import matplotlib.pyplot as plt\n",
"\n",
"def f(theta):\n",
" return -2.2067e-12 * (theta**4 - 81e8)\n",
"\n",
"def rk4(theta0, h, steps):\n",
" theta = theta0\n",
" values = [theta]\n",
" for _ in range(steps):\n",
" k1 = h * f(theta)\n",
" k2 = h * f(theta + 0.5 * k1)\n",
" k3 = h * f(theta + 0.5 * k2)\n",
" k4 = h * f(theta + k3)\n",
" theta += (1/6)*(k1 + 2*k2 + 2*k3 + k4)\n",
" values.append(theta)\n",
" return values\n",
"\n",
"theta0 = 1200\n",
"h_values = [240, 480]\n",
"t_end = 480\n",
"\n",
"plt.figure()\n",
"for h in h_values:\n",
" steps = int(t_end / h)\n",
" theta_vals = rk4(theta0, h, steps)\n",
" times = np.linspace(0, t_end, steps+1)\n",
" plt.plot(times, theta_vals, label=f'h = {h}')\n",
"\n",
"plt.xlabel(\"Time (s)\")\n",
"plt.ylabel(\"Temperature (K)\")\n",
"plt.legend()\n",
"plt.grid(True)\n",
"plt.show()\n"
]
},
{
"cell_type": "code",
"execution_count": 7,
"id": "6bf08c81-cbd0-42d7-be39-2d52ac000584",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Final temperatures at t = 480 s:\n",
"h = 240: θ = 594.9126 K\n",
"h = 480: θ = -90.2779 K\n"
]
},
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAk0AAAGwCAYAAAC0HlECAAAAOnRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjEwLjAsIGh0dHBzOi8vbWF0cGxvdGxpYi5vcmcvlHJYcgAAAAlwSFlzAA
"text/plain": [
"<Figure size 640x480 with 1 Axes>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"import numpy as np\n",
"import matplotlib.pyplot as plt\n",
"\n",
"def f(theta):\n",
" return -2.2067e-12 * (theta**4 - 81e8)\n",
"\n",
"def rk4(theta0, h, steps):\n",
" theta = theta0\n",
" values = [theta]\n",
" for _ in range(steps):\n",
" k1 = h * f(theta)\n",
" k2 = h * f(theta + 0.5 * k1)\n",
" k3 = h * f(theta + 0.5 * k2)\n",
" k4 = h * f(theta + k3)\n",
" theta += (1/6)*(k1 + 2*k2 + 2*k3 + k4)\n",
" values.append(theta)\n",
" return values\n",
"\n",
"theta0 = 1200\n",
"h_values = [240, 480]\n",
"t_end = 480\n",
"# Print final temperatures separately\n",
"print(\"Final temperatures at t = 480 s:\")\n",
"for h, temp in final_temps:\n",
" print(f\"h = {h}: θ = {temp:.4f} K\")\n",
"# Store final temperatures for display\n",
"final_temps = []\n",
"\n",
"plt.figure()\n",
"for h in h_values:\n",
" steps = int(t_end / h)\n",
" theta_vals = rk4(theta0, h, steps)\n",
" times = np.linspace(0, t_end, steps+1)\n",
" plt.plot(times, theta_vals, label=f'h = {h}')\n",
" final_temps.append((h, theta_vals[-1]))\n",
"\n",
"plt.xlabel(\"Time (s)\")\n",
"plt.ylabel(\"Temperature (K)\")\n",
"plt.legend()\n",
"plt.grid(True)\n",
"plt.show()\n",
"\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": 11,
"id": "85d23310-06ae-41fc-83cd-cd0caf7bf212",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"x = 0.00, y = 1.0000\n",
"x = 0.10, y = 1.1103\n",
"x = 0.20, y = 1.2428\n",
"x = 0.30, y = 1.3997\n",
"x = 0.40, y = 1.5836\n",
"x = 0.50, y = 1.7974\n",
"x = 0.60, y = 2.0442\n",
"x = 0.70, y = 2.3275\n",
"x = 0.80, y = 2.6511\n",
"x = 0.90, y = 3.0192\n",
"x = 1.00, y = 3.4366\n"
]
}
],
"source": [
" def f(x, y):\n",
" # Example: dy/dx = f(x, y) = x + y\n",
" return x + y\n",
"\n",
"def rk4_general(x0, y0, h, steps):\n",
" x = x0\n",
" y = y0\n",
" results = [(x, y)]\n",
" for _ in range(steps):\n",
" k1 = h * f(x, y)\n",
" k2 = h * f(x + 0.5 * h, y + 0.5 * k1)\n",
" k3 = h * f(x + 0.5 * h, y + 0.5 * k2)\n",
" k4 = h * f(x + h, y + k3)\n",
" y += (1/6)*(k1 + 2*k2 + 2*k3 + k4)\n",
" x += h\n",
" results.append((x, y))\n",
" return results\n",
"\n",
"# Example usage:\n",
"x0 = 0\n",
"y0 = 1\n",
"h = 0.1\n",
"steps = 10\n",
"\n",
"values = rk4_general(x0, y0, h, steps)\n",
"for xi, yi in values:\n",
" print(f\"x = {xi:.2f}, y = {yi:.4f}\")\n"
]
},
{
"cell_type": "code",
"execution_count": 12,
"id": "691b6cda-6f04-4ff9-8379-1a311ac4ad8c",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"x = 1.00, y = 3.4366\n"
]
}
],
"source": [
"def f(x, y):\n",
" # Example: dy/dx = f(x, y) = x + y\n",
" return x + y\n",
"\n",
"def rk4_general(x0, y0, h, steps):\n",
" x = x0\n",
" y = y0\n",
" results = [(x, y)]\n",
" for _ in range(steps):\n",
" k1 = h * f(x, y)\n",
" k2 = h * f(x + 0.5 * h, y + 0.5 * k1)\n",
" k3 = h * f(x + 0.5 * h, y + 0.5 * k2)\n",
" k4 = h * f(x + h, y + k3)\n",
" y += (1/6)*(k1 + 2*k2 + 2*k3 + k4)\n",
" x += h\n",
" results.append((x, y))\n",
" return results\n",
"x0 = 0\n",
"y0 = 1\n",
"h = 0.1\n",
"steps = 10\n",
"\n",
"values = rk4_general(x0, y0, h, steps)\n",
"\n",
"# Print only the final value\n",
"xf, yf = values[-1]\n",
"print(f\"x = {xf:.2f}, y = {yf:.4f}\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "5cc71ba1-b15f-486e-b83c-48740c4ca31e",
"metadata": {},
"outputs": [],
"source": [
"#ex. dy/dx=x**2+y**2\n",
"import numpy as np\n",
"\n",
"def rk4_single_step(f, x, y, h):\n",
" \"\"\"Computes one step of the RK4 method.\"\"\"\n",
" k1 = h * f(x, y)\n",
" k2 = h * f(x + h / 2, y + k1 / 2)\n",
" k3 = h * f(x + h / 2, y + k2 / 2)\n",
" k4 = h * f(x + h, y + k3)\n",
" return y + (k1 + 2*k2 + 2*k3 + k4) / 6\n",
"\n",
"# Given differential equation\n",
"def f(x, y):\n",
" return x**2 + y**2\n",
"\n",
"# Initial conditions\n",
"x0, y0 = 1, 1.2\n",
"h = 0.05\n",
"x_target = 1.05\n",
"\n",
"# Compute y at x=1.05\n",
"y_target = rk4_single_step(f, x0, y0, h)\n",
"\n",
"print(f\"y({x_target}) = {y_target:.6f}\")\n",
".\n"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.13.1"
}
},
"nbformat": 4,
"nbformat_minor": 5
}

You might also like