0% found this document useful (0 votes)
14 views

Numrcalallinone.ipynb - Colab

Uploaded by

Zakawat Sadi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Numrcalallinone.ipynb - Colab

Uploaded by

Zakawat Sadi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 42

import numpy as np

import matplotlib.pyplot as plt


import pandas as pd
import seaborn as sns
from mpl_toolkits.mplot3d import Axes3D

# Jacobi method
def jacobi(A, b, x0, tol, max_iterations):
n = len(A)
x = x0.copy()
x_new = x0.copy()

for iteration in range(max_iterations):


for i in range(n):
sum_ = np.dot(A[i, :], x) - A[i, i] * x[i]
x_new[i] = (b[i] - sum_) / A[i, i]

# Check for convergence


if np.linalg.norm(x_new - x) < tol:
break

x = x_new.copy()

return x_new, iteration + 1

Example:

# Define the coefficient matrix A and vector b


A = np.array([[4, -1, 0],
[-1, 4, -1],
[0, -1, 4]])

b = np.array([15, 10, 10])

# Initial guess x0
x0 = np.zeros(len(b))

# Tolerance and maximum number of iterations


tol = 1e-10
max_iterations = 100

# Solve using Jacobi method


solution, iterations = jacobi(A, b, x0, tol, max_iterations)

# Display the solution and number of iterations


print("Solution:", solution)
print("Iterations:", iterations)

Solution: [4.91071429 4.64285714 3.66071429]


Iterations: 25

Table sulution

# Display the result as a table


df = pd.DataFrame({
'Variable': ['x1', 'x2', 'x3'],
'Solution': solution
})
print(df)

Variable Solution
0 x1 4.910714
1 x2 4.642857
2 x3 3.660714

# Line chart
plt.figure(figsize=(8, 6))
plt.plot(['x1', 'x2', 'x3'], solution, marker='o', linestyle='-', color='b')
plt.title('Jacobi Method Solution - Line Chart')
plt.xlabel('Variables')
plt.ylabel('Values')
plt.grid(True)
plt.show()

# Bar chart
plt.figure(figsize=(8, 6))
plt.bar(['x1', 'x2', 'x3'], solution, color='orange')
plt.title('Jacobi Method Solution - Bar Chart')
plt.xlabel('Variables')
plt.ylabel('Values')
plt.show()

# Mesh chart (3D plot of the solution)


fig = plt.figure(figsize=(10, 7))
ax = fig.add_subplot(111, projection='3d')
x = np.array([1, 2, 3])
y = solution
z = np.zeros(3)

# Create the mesh


ax.plot_trisurf(x, y, z, color='cyan')
ax.set_title('Jacobi Method Solution - Mesh Chart')
ax.set_xlabel('Variable Index')
ax.set_ylabel('Solution Value')
ax.set_zlabel('Zero Plane')
plt.show()

# Violin chart
plt.figure(figsize=(8, 6))
sns.violinplot(data=solution, inner="point", linewidth=2)
plt.title('Jacobi Method Solution - Violin Chart')
plt.show()
/usr/local/lib/python3.10/dist-packages/seaborn/_base.py:949: FutureWarning: When grouping with a length-1 list-like, you will need to p
data_subset = grouped_data.get_group(pd_key)

Gauss siedal mthod

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
from mpl_toolkits.mplot3d import Axes3D

# Gauss-Seidel method
def gauss_seidel(A, b, x0, tol, max_iterations):
n = len(A)
x = x0.copy()
iteration_data = []

for iteration in range(max_iterations):


x_old = x.copy()
for i in range(n):
sum_ = np.dot(A[i, :], x) - A[i, i] * x[i]
x[i] = (b[i] - sum_) / A[i, i]

iteration_data.append(x.copy())

# Check for convergence


if np.linalg.norm(x - x_old) < tol:
break

return x, iteration_data, iteration + 1

# Define the coefficient matrix A and vector b


A = np.array([[4, -1, 0],
[-1, 4, -1],
[0, -1, 4]])

b = np.array([15, 10, 10])

# Initial guess x0
x0 = np.zeros(len(b))

# Tolerance and maximum number of iterations


tol = 1e-10
max_iterations = 100

# Solve using Gauss-Seidel method


solution, iteration_data, iterations = gauss_seidel(A, b, x0, tol, max_iterations)

# Display the solution and number of iterations


print("Solution:", solution)
print("Iterations:", iterations)

Solution: [4.91071429 4.64285714 3.66071429]


Iterations: 14

# Display the result as a table (for the last iteration)


df_iterations = pd.DataFrame(iteration_data, columns=['x1', 'x2', 'x3'])
df_iterations['Iteration'] = range(1, len(df_iterations) + 1)
print(df_iterations)

x1 x2 x3 Iteration
0 3.750000 3.437500 3.359375 1
1 4.609375 4.492188 3.623047 2
2 4.873047 4.624023 3.656006 3
3 4.906006 4.640503 3.660126 4
4 4.910126 4.642563 3.660641 5
5 4.910641 4.642820 3.660705 6
6 4.910705 4.642853 3.660713 7
7 4.910713 4.642857 3.660714 8
8 4.910714 4.642857 3.660714 9
9 4.910714 4.642857 3.660714 10
10 4.910714 4.642857 3.660714 11
11 4.910714 4.642857 3.660714 12
12 4.910714 4.642857 3.660714 13
13 4.910714 4.642857 3.660714 14

# Line chart showing iterative solution


plt.figure(figsize=(8, 6))
plt.plot(df_iterations['Iteration'], df_iterations['x1'], label='x1', marker='o')
plt.plot(df_iterations['Iteration'], df_iterations['x2'], label='x2', marker='o')
plt.plot(df_iterations['Iteration'], df_iterations['x3'], label='x3', marker='o')
plt.title('Gauss-Seidel Method Iterative Solution - Line Chart')
plt.xlabel('Iterations')
plt.ylabel('Variable Values')
plt.grid(True)
plt.legend()
plt.show()

# Bar chart (final solution after iterations)


plt.figure(figsize=(8, 6))
plt.bar(['x1', 'x2', 'x3'], solution, color='orange')
plt.title('Gauss-Seidel Method Final Solution - Bar Chart')
plt.xlabel('Variables')
plt.ylabel('Values')
plt.show()

# Mesh chart (3D plot of the final solution)


fig = plt.figure(figsize=(10, 7))
ax = fig.add_subplot(111, projection='3d')
x = np.array([1, 2, 3])
y = solution
z = np.zeros(3)

# Create the mesh


ax.plot_trisurf(x, y, z, color='cyan')
ax.set_title('Gauss-Seidel Method Final Solution - Mesh Chart')
ax.set_xlabel('Variable Index')
ax.set_ylabel('Solution Value')
ax.set_zlabel('Zero Plane')
plt.show()
# Violin chart of the final solution
plt.figure(figsize=(8, 6))
sns.violinplot(data=solution, inner="point", linewidth=2)
plt.title('Gauss-Seidel Method Final Solution - Violin Chart')
plt.show()

/usr/local/lib/python3.10/dist-packages/seaborn/_base.py:949: FutureWarning: When grouping with a length-1 list-like, you will need to p
data_subset = grouped_data.get_group(pd_key)

chapter numerical differentiation

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
import seaborn as sns
from mpl_toolkits.mplot3d import Axes3D

# Newton Divided Difference method


def divided_diff(x, y):
n = len(x)
diff_table = np.zeros((n, n))
diff_table[:, 0] = y

for j in range(1, n):


for i in range(n - j):
diff_table[i][j] = (diff_table[i + 1][j - 1] - diff_table[i][j - 1]) / (x[i + j] - x[i])

return diff_table

# Forward Difference method


def forward_diff(x, y):
n = len(x)
fwd_table = np.zeros((n, n))
fwd_table[:, 0] = y

for j in range(1, n):


for i in range(n - j):
fwd_table[i][j] = fwd_table[i + 1][j - 1] - fwd_table[i][j - 1]

return fwd_table

# Function to evaluate the Newton polynomial


def newton_polynomial(x, x_vals, diff_table):
n = len(x_vals)
result = diff_table[0, 0]
product_term = 1

for i in range(1, n):


product_term *= (x - x_vals[i - 1])
result += diff_table[0, i] * product_term

return result

# Example points
x_vals = np.array([1, 2, 3, 4])
y_vals = np.array([1, 8, 27, 64])

# Calculate divided differences


div_diff_table = divided_diff(x_vals, y_vals)

# Calculate forward differences


fwd_diff_table = forward_diff(x_vals, y_vals)

# Display the divided difference table


df_div_diff = pd.DataFrame(div_diff_table)
df_div_diff.columns = [f'Delta^{i}' for i in range(len(x_vals))]
print("Divided Difference Table:")
print(df_div_diff)

# Display the forward difference table


df_fwd_diff = pd.DataFrame(fwd_diff_table)
df_fwd_diff.columns = [f'Delta^{i}' for i in range(len(x_vals))]
print("\nForward Difference Table:")
print(df_fwd_diff)

Divided Difference Table:


Delta^0 Delta^1 Delta^2 Delta^3
0 1.0 7.0 6.0 1.0
1 8.0 19.0 9.0 0.0
2 27.0 37.0 0.0 0.0
3 64.0 0.0 0.0 0.0

Forward Difference Table:


Delta^0 Delta^1 Delta^2 Delta^3
0 1.0 7.0 12.0 6.0
1 8.0 19.0 18.0 0.0
2 27.0 37.0 0.0 0.0
3 64.0 0.0 0.0 0.0
# Display the divided difference table
print("Newton Divided Difference Table:")
print(df_div_diff)

# Display the forward difference table


print("\nForward Difference Table:")
print(df_fwd_diff)

Newton Divided Difference Table:


Delta^0 Delta^1 Delta^2 Delta^3
0 1.0 7.0 6.0 1.0
1 8.0 19.0 9.0 0.0
2 27.0 37.0 0.0 0.0
3 64.0 0.0 0.0 0.0

Forward Difference Table:


Delta^0 Delta^1 Delta^2 Delta^3
0 1.0 7.0 12.0 6.0
1 8.0 19.0 18.0 0.0
2 27.0 37.0 0.0 0.0
3 64.0 0.0 0.0 0.0

# Generate values for the interpolated polynomial


x_interp = np.linspace(min(x_vals), max(x_vals), 100)
y_interp = [newton_polynomial(x, x_vals, div_diff_table) for x in x_interp]

# Line chart showing the interpolated polynomial


plt.figure(figsize=(8, 6))
plt.plot(x_interp, y_interp, label='Interpolated Polynomial', color='blue')
plt.scatter(x_vals, y_vals, label='Original Points', color='red')
plt.title('Newton Divided Difference Polynomial - Line Chart')
plt.xlabel('x')
plt.ylabel('f(x)')
plt.grid(True)
plt.legend()
plt.show()
# Bar chart of the divided differences (first column)
plt.figure(figsize=(8, 6))
plt.bar(range(len(div_diff_table)), div_diff_table[:, 0], color='orange')
plt.title('Newton Divided Differences - Bar Chart')
plt.xlabel('Index')
plt.ylabel('Divided Difference Value')
plt.show()

# Mesh chart (3D plot of divided differences)


fig = plt.figure(figsize=(10, 7))
ax = fig.add_subplot(111, projection='3d')
x = np.arange(len(div_diff_table))
y = div_diff_table[:, 0]
z = np.zeros(len(div_diff_table))

# Create the mesh


ax.plot_trisurf(x, y, z, color='cyan')
ax.set_title('Newton Divided Differences - Mesh Chart')
ax.set_xlabel('Index')
ax.set_ylabel('Difference Value')
ax.set_zlabel('Zero Plane')
plt.show()
# Violin chart of the first column of divided differences
plt.figure(figsize=(8, 6))
sns.violinplot(data=div_diff_table[:, 0], inner="point", linewidth=2)
plt.title('Newton Divided Differences - Violin Chart')
plt.show()

/usr/local/lib/python3.10/dist-packages/seaborn/_base.py:949: FutureWarning: When grouping with a length-1 list-like, you will need to p
data_subset = grouped_data.get_group(pd_key)

Backward differnce

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from mpl_toolkits.mplot3d import Axes3D

# Newton's Divided Difference method using Backward Differences


def divided_diff_backward(x, y):
n = len(x)
diff_table = np.zeros((n, n))
diff_table[:, 0] = y # First column is y values

for j in range(1, n):


for i in range(j, n):
diff_table[i, j] = (diff_table[i, j - 1] - diff_table[i - 1, j - 1]) / (x[i] - x[i - j])

return diff_table

# Function to evaluate the Newton Backward polynomial


def newton_backward_polynomial(x, x_vals, diff_table):
n = len(x_vals)
result = diff_table[-1, 0] # Start with the last element
product_term = 1

for i in range(1, n):


product_term *= (x - x_vals[-i])
result += diff_table[-1, i]

# Example data points


x_vals = np.array([1, 2, 3, 4])
y_vals = np.array([1, 8, 27, 64])

# Calculate divided differences (backward difference table)


diff_table_backward = divided_diff_backward(x_vals, y_vals)

# Display the backward divided difference table


df_diff_table = pd.DataFrame(diff_table_backward)
df_diff_table.columns = [f'Delta^{i}' for i in range(len(x_vals))]
print("Backward Divided Difference Table:")
print(df_diff_table)

Backward Divided Difference Table:


Delta^0 Delta^1 Delta^2 Delta^3
0 1.0 0.0 0.0 0.0
1 8.0 7.0 0.0 0.0
2 27.0 19.0 6.0 0.0
3 64.0 37.0 9.0 1.0

# Display the backward difference table


print("Backward Divided Difference Table:")
print(df_diff_table)

Backward Divided Difference Table:


Delta^0 Delta^1 Delta^2 Delta^3
0 1.0 0.0 0.0 0.0
1 8.0 7.0 0.0 0.0
2 27.0 19.0 6.0 0.0
3 64.0 37.0 9.0 1.0

# Generate values for the interpolated polynomial


x_interp = np.linspace(min(x_vals), max(x_vals), 100)
y_interp = [newton_backward_polynomial(x, x_vals, diff_table_backward) for x in x_interp]

# Line chart showing the interpolated polynomial


plt.figure(figsize=(8, 6))
plt.plot(x_interp, y_interp, label='Interpolated Polynomial', color='blue')
plt.scatter(x_vals, y_vals, label='Original Points', color='red')
plt.title('Newton Backward Difference Polynomial - Line Chart')
plt.xlabel('x')
plt.ylabel('f(x)')
plt.grid(True)
plt.legend()
plt.show()
# Bar chart of the backward divided differences (first column)
plt.figure(figsize=(8, 6))
plt.bar(range(len(diff_table_backward)), diff_table_backward[:, 0], color='orange')
plt.title('Backward Divided Differences - Bar Chart')
plt.xlabel('Index')
plt.ylabel('Difference Value')
plt.show()

# Mesh chart (3D plot of backward divided differences)


fig = plt.figure(figsize=(10, 7))
ax = fig.add_subplot(111, projection='3d')
x = np.arange(len(diff_table_backward))
y = diff_table_backward[:, 0]
z = np.zeros(len(diff_table_backward))
# Create the mesh
ax.plot_trisurf(x, y, z, color='cyan')
ax.set_title('Backward Divided Differences - Mesh Chart')
ax.set_xlabel('Index')
ax.set_ylabel('Difference Value')
ax.set_zlabel('Zero Plane')
plt.show()

central difference

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from mpl_toolkits.mplot3d import Axes3D

# Newton's Divided Difference method with Central Differences


def divided_diff_central(x, y):
n = len(x)
diff_table = np.zeros((n, n))
diff_table[:, 0] = y # First column is y values

for j in range(1, n):


for i in range(j, n - j):
diff_table[i, j] = (diff_table[i + 1, j - 1] - diff_table[i - 1, j - 1]) / (x[i + j] - x[i - j])

return diff_table

# Function to evaluate the Newton Central polynomial


def newton_central_polynomial(x, x_vals, diff_table):
n = len(x_vals)
result = diff_table[n//2, 0] # Start with the middle element for central difference
product_term = 1

for i in range(1, n):


product_term *= (x - x_vals[n//2 - i])
result += diff_table[n//2, i] * product_term

return result

# Example data points


x_vals = np.array([1, 2, 3, 4, 5])
y_vals = np.array([1, 8, 27, 64, 125])

# Calculate divided differences (central difference table)


diff_table_central = divided_diff_central(x_vals, y_vals)

# Display the central divided difference table


df_diff_table = pd.DataFrame(diff_table_central)
df_diff_table.columns = [f'Delta^{i}' for i in range(len(x_vals))]
print("Central Divided Difference Table:")
print(df_diff_table)

Central Divided Difference Table:


Delta^0 Delta^1 Delta^2 Delta^3 Delta^4
0 1.0 0.0 0.0 0.0 0.0
1 8.0 13.0 0.0 0.0 0.0
2 27.0 28.0 9.0 0.0 0.0
3 64.0 49.0 0.0 0.0 0.0
4 125.0 0.0 0.0 0.0 0.0

# Generate values for the interpolated polynomial


x_interp = np.linspace(min(x_vals), max(x_vals), 100)
y_interp = [newton_central_polynomial(x, x_vals, diff_table_central) for x in x_interp]

# Line chart showing the interpolated polynomial


plt.figure(figsize=(8, 6))
plt.plot(x_interp, y_interp, label='Interpolated Polynomial', color='blue')
plt.scatter(x_vals, y_vals, label='Original Points', color='red')
plt.title('Newton Central Difference Polynomial - Line Chart')
plt.xlabel('x')
plt.ylabel('f(x)')
plt.grid(True)
plt.legend()
plt.show()

# Mesh chart (3D plot of central divided differences)


fig = plt.figure(figsize=(10, 7))
ax = fig.add_subplot(111, projection='3d')
x = np.arange(len(diff_table_central))
y = diff_table_central[:, 0]
z = np.zeros(len(diff_table_central))

# Create the mesh


ax.plot_trisurf(x, y, z, color='cyan')
ax.set_title('Central Divided Differences - Mesh Chart')
ax.set_xlabel('Index')
ax.set_ylabel('Difference Value')
ax.set_zlabel('Zero Plane')
plt.show()

simpson 1/3

Simpson’s 1/3 method is a numerical integration technique used to approximate the value of a definite integral. It uses parabolic segments to
approximate the area under a curve. Simpson’s 1/3 rule is applied when the number of intervals is even.

The formula for Simpson's 1/3 rule is:

∫ 𝑎 𝑏 𝑓 ( 𝑥 ) 𝑑 𝑥 ≈ ℎ 3 [ 𝑓 ( 𝑥 0 ) + 4 ∑ 𝑖 = 1 , 3 , 5 , . . . 𝑛 − 1 𝑓 ( 𝑥 𝑖 ) + 2 ∑ 𝑖 = 2 , 4 , 6 , . . . 𝑛 − 2 𝑓 ( 𝑥 𝑖 ) + 𝑓 ( 𝑥 𝑛 ) ] ∫ a b​f(x)dx≈ 3 h​[f(x 0​)+4 i=1,3,5,... ∑


n−1​f(x i​)+2 i=2,4,6,... ∑ n−2​f(x i​)+f(x n​)] Where:

ℎ = 𝑏 − 𝑎 𝑛 h= n b−a​is the width of each interval. 𝑛 n is the number of intervals (must be even).

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

# Simpson's 1/3 method implementation


def simpsons_one_third(x, y):
n = len(x) - 1 # Number of intervals
if n % 2 != 0:
raise ValueError("Number of intervals must be even for Simpson's 1/3 rule")

h = (x[-1] - x[0]) / n

# Simpson's 1/3 rule formula


integral = y[0] + y[-1] # First and last terms
integral += 4 * np.sum(y[1:n:2]) # Sum of odd-indexed y values
integral += 2 * np.sum(y[2:n-1:2]) # Sum of even-indexed y values
integral = (h / 3) * integral

return integral

# Example function for integration: f(x) = x^2


def f(x):
return x ** 2
# Define the interval and number of points
a, b = 0, 4 # Integration limits
n = 4 # Must be even for Simpson's 1/3 rule

# Generate x values (equally spaced)


x_vals = np.linspace(a, b, n + 1)

# Calculate corresponding y values


y_vals = f(x_vals)

# Calculate the integral using Simpson's 1/3 method


integral = simpsons_one_third(x_vals, y_vals)

# Display iterative results in a table


df = pd.DataFrame({"x": x_vals, "y": y_vals})
print("Iterative Output (x, y values):")
print(df)

# Print the final result


print(f"\nApproximate integral using Simpson's 1/3 method: {integral}")

Iterative Output (x, y values):


x y
0 0.0 0.0
1 1.0 1.0
2 2.0 4.0
3 3.0 9.0
4 4.0 16.0

Approximate integral using Simpson's 1/3 method: 21.333333333333332

# Line chart showing the function and the parabolic segments


x_interp = np.linspace(a, b, 100) # Interpolated x values for smooth plot
y_interp = f(x_interp)

plt.figure(figsize=(8, 6))
plt.plot(x_interp, y_interp, label='f(x) = x^2', color='blue')
plt.scatter(x_vals, y_vals, label='Sampled Points', color='red')
plt.fill_between(x_interp, y_interp, color='skyblue', alpha=0.3)
plt.title("Simpson's 1/3 Method - Line Chart")
plt.xlabel('x')
plt.ylabel('f(x)')
plt.legend()
plt.grid(True)
plt.show()
# Mesh chart (3D plot of the function values and x)
fig = plt.figure(figsize=(10, 7))
ax = fig.add_subplot(111, projection='3d')
ax.plot_trisurf(x_vals, y_vals, np.zeros_like(x_vals), color='cyan')

# Labeling the axes


ax.set_title("Simpson's 1/3 Method - Mesh Chart")
ax.set_xlabel('x')
ax.set_ylabel('f(x)')
ax.set_zlabel('Zero Plane')

plt.show()
simpson 3/8

The Simpson's 3/8 rule is another numerical integration technique similar to Simpson's 1/3 rule but is used when the number of intervals is a
multiple of 3. The formula for Simpson's 3/8 rule is:

∫ 𝑎 𝑏 𝑓 ( 𝑥 ) 𝑑 𝑥 ≈ 3 ℎ 8 [ 𝑓 ( 𝑥 0 ) + 3 ∑ 𝑖 = 1 , 2 , 4 , 5 , … 𝑛 − 1 𝑓 ( 𝑥 𝑖 ) + 2 ∑ 𝑖 = 3 , 6 , 9 , … 𝑛 − 3 𝑓 ( 𝑥 𝑖 ) + 𝑓 ( 𝑥 𝑛 ) ] ∫ a b​f(x)dx≈ 8 3h​[f(x 0​)+3


i=1,2,4,5,… ∑ n−1​f(x i​)+2 i=3,6,9,… ∑ n−3​f(x i​)+f(x n​)] Where:

ℎ = 𝑏 − 𝑎 𝑛 h= n b−a​is the width of each interval. 𝑛 n is the number of intervals (must be a multiple of 3).

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

# Simpson's 3/8 method implementation


def simpsons_three_eighth(x, y):
n = len(x) - 1 # Number of intervals
if n % 3 != 0:
raise ValueError("Number of intervals must be a multiple of 3 for Simpson's 3/8 rule")

h = (x[-1] - x[0]) / n

# Simpson's 3/8 rule formula


integral = y[0] + y[-1] # First and last terms
integral += 3 * np.sum(y[1:n:3]) # Sum of terms indexed 1, 4, 7, etc.
integral += 3 * np.sum(y[2:n:3]) # Sum of terms indexed 2, 5, 8, etc.
integral += 2 * np.sum(y[3:n-3:3]) # Sum of terms indexed 3, 6, 9, etc.
integral = (3 * h / 8) * integral

return integral

# Example function for integration: f(x) = x^2


def f(x):
return x ** 2

# Define the interval and number of points


a, b = 0, 3 # Integration limits
n = 3 # Must be a multiple of 3 for Simpson's 3/8 rule

# Generate x values (equally spaced)


x_vals = np.linspace(a, b, n + 1)

# Calculate corresponding y values


y_vals = f(x_vals)

# Calculate the integral using Simpson's 3/8 method


integral = simpsons_three_eighth(x_vals, y_vals)

# Display iterative results in a table


df = pd.DataFrame({"x": x_vals, "y": y_vals})
print("Iterative Output (x, y values):")
print(df)

# Print the final result


print(f"\nApproximate integral using Simpson's 3/8 method: {integral}")

Iterative Output (x, y values):


x y
0 0.0 0.0
1 1.0 1.0
2 2.0 4.0
3 3.0 9.0

Approximate integral using Simpson's 3/8 method: 9.0

# Line chart showing the function and the parabolic segments


x_interp = np.linspace(a, b, 100) # Interpolated x values for smooth plot
y_interp = f(x_interp)

plt.figure(figsize=(8, 6))
plt.plot(x_interp, y_interp, label='f(x) = x^2', color='blue')
plt.scatter(x_vals, y_vals, label='Sampled Points', color='red')
plt.fill_between(x_interp, y_interp, color='skyblue', alpha=0.3)
plt.title("Simpson's 3/8 Method - Line Chart")
plt.xlabel('x')
plt.ylabel('f(x)')
plt.legend()
plt.grid(True)
plt.show()

# Mesh chart (3D plot of the function values and x)


fig = plt.figure(figsize=(10, 7))
ax = fig.add_subplot(111, projection='3d')
ax.plot_trisurf(x_vals, y_vals, np.zeros_like(x_vals), color='cyan')

# Labeling the axes


ax.set_title("Simpson's 3/8 Method - Mesh Chart")
ax.set_xlabel('x')
ax.set_ylabel('f(x)')
ax.set_zlabel('Zero Plane')

plt.show()
Eulers method

Problem: Solving the ODE 𝑑 𝑦 𝑑 𝑥 = 𝑓 ( 𝑥 , 𝑦 ) dx dy​=f(x,y) Let’s take an example of the differential equation 𝑑 𝑦 𝑑 𝑥 = 𝑥 + 𝑦 dx dy​=x+y with the
initial condition 𝑦 ( 0 ) = 1 y(0)=1, and we'll solve it over the interval [ 0 , 2 ] [0,2].

Step-by-Step Guide Step 1: Euler's Method Implementation Euler's method formula is:

𝑦 𝑖 + 1 = 𝑦 𝑖 + ℎ ⋅ 𝑓 ( 𝑥 𝑖 , 𝑦 𝑖 ) y i+1​=y i​+h⋅f(x i​,y i​) Where:

ℎ h is the step size. 𝑦 𝑖 + 1 y i+1​is the next value of 𝑦 y. 𝑓 ( 𝑥 𝑖 , 𝑦 𝑖 ) f(x i​,y i​) represents the derivative at ( 𝑥 𝑖 , 𝑦 𝑖 ) (x i​,y i​).

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

# Euler's method implementation


def euler_method(f, x0, y0, h, x_end):
x_vals = [x0]
y_vals = [y0]

x = x0
y = y0

while x < x_end:


y = y + h * f(x, y)
x = x + h
x_vals.append(x)
y_vals.append(y)

return np.array(x_vals), np.array(y_vals)

# Differential equation: dy/dx = x + y


def f(x, y):
return x + y

# Initial conditions and step size


x0 = 0
y0 = 1
h = 0.1
x_end = 2
# Apply Euler's method
x_vals, y_vals = euler_method(f, x0, y0, h, x_end)

# Display iterative results in a table


df = pd.DataFrame({"x": x_vals, "y": y_vals})
print("Iterative Output (x, y values):")
print(df)

Iterative Output (x, y values):


x y
0 0.0 1.000000
1 0.1 1.100000
2 0.2 1.220000
3 0.3 1.362000
4 0.4 1.528200
5 0.5 1.721020
6 0.6 1.943122
7 0.7 2.197434
8 0.8 2.487178
9 0.9 2.815895
10 1.0 3.187485
11 1.1 3.606233
12 1.2 4.076857
13 1.3 4.604542
14 1.4 5.194997
15 1.5 5.854496
16 1.6 6.589946
17 1.7 7.408941
18 1.8 8.319835
19 1.9 9.331818
20 2.0 10.455000

# Line chart showing Euler's method approximation


plt.figure(figsize=(8, 6))
plt.plot(x_vals, y_vals, label='Euler Approximation', color='blue', marker='o')
plt.title("Euler's Method - Line Chart")
plt.xlabel('x')
plt.ylabel('y')
plt.grid(True)
plt.legend()
plt.show()

# Mesh chart (3D plot of x, y)


fig = plt.figure(figsize=(10, 7))
ax = fig.add_subplot(111, projection='3d')
ax.plot_trisurf(x_vals, y_vals, np.zeros_like(x_vals), color='cyan')

# Labeling the axes


ax.set_title("Euler's Method - Mesh Chart")
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('Zero Plane')

plt.show()

Heuns method

Heun's method, also known as the improved Euler method, is a numerical technique used to solve ordinary differential equations (ODEs). It's
more accurate than Euler's method because it averages the slopes at the beginning and end of each step.

Formula for Heun's Method For the differential equation 𝑑 𝑦 𝑑 𝑥 = 𝑓 ( 𝑥 , 𝑦 ) dx dy​=f(x,y), the Heun's method is given by:

𝑦 𝑖 + 1 = 𝑦 𝑖 + ℎ 2 ( 𝑓 ( 𝑥 𝑖 , 𝑦 𝑖 ) + 𝑓 ( 𝑥 𝑖 + 1 , 𝑦 predict ) ) y i+1​=y i​

2 h​(f(x i​,y i​)+f(x i+1​,y predict​)) Where:

ℎ h is the step size. 𝑦 predict = 𝑦 𝑖 + ℎ ⋅ 𝑓 ( 𝑥 𝑖 , 𝑦 𝑖 ) y predict​=y i​+h⋅f(x i​,y i​) is the predicted value of 𝑦 y at 𝑥 𝑖 + 1 x i+1​. Example: Solving 𝑑 𝑦 𝑑 𝑥 =
𝑥 + 𝑦 dx dy​=x+y Let's solve the differential equation 𝑑 𝑦 𝑑 𝑥 = 𝑥 + 𝑦 dx dy​=x+y with an initial condition 𝑦 ( 0 ) = 1 y(0)=1, and step size ℎ = 0.1
h=0.1 over the interval [ 0 , 2 ] [0,2].

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

# Heun's method implementation


def heuns_method(f, x0, y0, h, x_end):
x_vals = [x0]
y_vals = [y0]

x = x0
y = y0

while x < x_end:


# Euler prediction
y_predict = y + h * f(x, y)
# Heun's method update
y = y + (h / 2) * (f(x, y) + f(x + h, y_predict))
x = x + h
x_vals.append(x)
y_vals.append(y)

return np.array(x_vals), np.array(y_vals)

# Differential equation: dy/dx = x + y


def f(x, y):
return x + y

# Initial conditions and step size


x0 = 0
y0 = 1
h = 0.1
x_end = 2

# Apply Heun's method


x_vals, y_vals = heuns_method(f, x0, y0, h, x_end)

# Display iterative results in a table


df = pd.DataFrame({"x": x_vals, "y": y_vals})
print("Iterative Output (x, y values):")
print(df)

Iterative Output (x, y values):


x y
0 0.0 1.000000
1 0.1 1.110000
2 0.2 1.242050
3 0.3 1.398465
4 0.4 1.581804
5 0.5 1.794894
6 0.6 2.040857
7 0.7 2.323147
8 0.8 2.645578
9 0.9 3.012364
10 1.0 3.428162
11 1.1 3.898119
12 1.2 4.427921
13 1.3 5.023853
14 1.4 5.692857
15 1.5 6.442607
16 1.6 7.281581
17 1.7 8.219147
18 1.8 9.265658
19 1.9 10.432552
20 2.0 11.732470

# Line chart showing Heun's method approximation


plt.figure(figsize=(8, 6))
plt.plot(x_vals, y_vals, label='Heun Approximation', color='blue', marker='o')
plt.title("Heun's Method - Line Chart")
plt.xlabel('x')
plt.ylabel('y')
plt.grid(True)
plt.legend()
plt.show()
# Mesh chart (3D plot of x, y)
fig = plt.figure(figsize=(10, 7))
ax = fig.add_subplot(111, projection='3d')
ax.plot_trisurf(x_vals, y_vals, np.zeros_like(x_vals), color='cyan')

# Labeling the axes


ax.set_title("Heun's Method - Mesh Chart")
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('Zero Plane')

plt.show()
Double-click (or enter) to edit

Rungee kutta second order method

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

# Runge-Kutta second-order method implementation


def runge_kutta_2nd_order(f, x0, y0, h, x_end):
x_vals = [x0]
y_vals = [y0]

x = x0
y = y0

while x < x_end:


k1 = f(x, y)
k2 = f(x + h / 2, y + h * k1 / 2)

y = y + h * k2
x = x + h

x_vals.append(x)
y_vals.append(y)

return np.array(x_vals), np.array(y_vals)

# Differential equation: dy/dx = x + y


def f(x, y):
return x + y

# Initial conditions and step size


x0 = 0
y0 = 1
h = 0.1
x_end = 2

# Apply Runge-Kutta 2nd order method


x_vals, y_vals = runge_kutta_2nd_order(f, x0, y0, h, x_end)

# Display iterative results in a table


df = pd.DataFrame({"x": x_vals, "y": y_vals})
print("Iterative Output (x, y values):")
print(df)

# Line chart showing Runge-Kutta method approximation


plt.figure(figsize=(8, 6))
plt.plot(x_vals, y_vals, label='Runge-Kutta Approximation', color='blue', marker='o')
plt.title("Runge-Kutta 2nd Order Method - Line Chart")
plt.xlabel('x')
plt.ylabel('y')
plt.grid(True)
plt.legend()
plt.show()

# Mesh chart (3D plot of x, y)


fig = plt.figure(figsize=(10, 7))
ax = fig.add_subplot(111, projection='3d')
ax.plot_trisurf(x_vals, y_vals, np.zeros_like(x_vals), color='cyan')

# Labeling the axes


ax.set_title("Runge-Kutta 2nd Order Method - Mesh Chart")
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('Zero Plane')

plt.show()
Iterative Output (x, y values):
x y
0 0.0 1.000000
1 0.1 1.110000
2 0.2 1.242050
3 0.3 1.398465
4 0.4 1.581804
5 0.5 1.794894
6 0.6 2.040857
7 0.7 2.323147
8 0.8 2.645578
9 0.9 3.012364
10 1.0 3.428162
11 1.1 3.898119
12 1.2 4.427921
13 1.3 5.023853
14 1.4 5.692857
15 1.5 6.442607
16 1.6 7.281581
17 1.7 8.219147
18 1.8 9.265658
19 1.9 10.432552
20 2.0 11.732470
Runge kutta 3rd order

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

# Runge-Kutta third-order method implementation


def runge_kutta_3rd_order(f, x0, y0, h, x_end):
x_vals = [x0]
y_vals = [y0]

x = x0
y = y0

while x < x_end:


k1 = f(x, y)
k2 = f(x + h / 2, y + h * k1 / 2)
k3 = f(x + h, y + h * k2)

y = y + (h / 6) * (k1 + 4 * k2 + k3)
x = x + h

x_vals.append(x)
y_vals.append(y)

return np.array(x_vals), np.array(y_vals)

# Differential equation: dy/dx = x + y


def f(x, y):
return x + y

# Initial conditions and step size


x0 = 0
y0 = 1
h = 0.1
x_end = 2

# Apply Runge-Kutta 3rd order method


x_vals, y_vals = runge_kutta_3rd_order(f, x0, y0, h, x_end)

# Display iterative results in a table


df = pd.DataFrame({"x": x_vals, "y": y_vals})
print("Iterative Output (x, y values):")
print(df)

# Line chart showing Runge-Kutta method approximation


plt.figure(figsize=(8, 6))
plt.plot(x_vals, y_vals, label='Runge-Kutta Approximation', color='blue', marker='o')
plt.title("Runge-Kutta 3rd Order Method - Line Chart")
plt.xlabel('x')
plt.ylabel('y')
plt.grid(True)
plt.legend()
plt.show()

# Mesh chart (3D plot of x, y)


fig = plt.figure(figsize=(10, 7))
ax = fig.add_subplot(111, projection='3d')
ax.plot_trisurf(x_vals, y_vals, np.zeros_like(x_vals), color='cyan')

# Labeling the axes


ax.set_title("Runge-Kutta 3rd Order Method - Mesh Chart")
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('Zero Plane')

plt.show()
Iterative Output (x, y values):
x y
0 0.0 1.000000
1 0.1 1.110167
2 0.2 1.242418
3 0.3 1.399076
4 0.4 1.582704
5 0.5 1.796136
6 0.6 2.042505
7 0.7 2.325272
8 0.8 2.648261
9 0.9 3.015699
10 1.0 3.432257
11 1.1 3.903096
12 1.2 4.433922
13 1.3 5.031036
14 1.4 5.701406
15 1.5 6.452729
16 1.6 7.293511
17 1.7 8.233155
18 1.8 9.282047
19 1.9 10.451669
20 2.0 11.754707
Rungee kutta 4th order

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

# Runge-Kutta fourth-order method implementation


def runge_kutta_4th_order(f, x0, y0, h, x_end):
x_vals = [x0]
y_vals = [y0]

x = x0
y = y0

while x < x_end:


k1 = f(x, y)
k2 = f(x + h / 2, y + h * k1 / 2)
k3 = f(x + h / 2, y + h * k2 / 2)
k4 = f(x + h, y + h * k3)

y = y + (h / 6) * (k1 + 2 * k2 + 2 * k3 + k4)
x = x + h

x_vals.append(x)
y_vals.append(y)

return np.array(x_vals), np.array(y_vals)

# Differential equation: dy/dx = x + y


def f(x, y):
return x + y

# Initial conditions and step size


x0 = 0
y0 = 1
h = 0.1
x_end = 2

# Apply Runge-Kutta 4th order method


x_vals, y_vals = runge_kutta_4th_order(f, x0, y0, h, x_end)

# Display iterative results in a table


df = pd.DataFrame({"x": x_vals, "y": y_vals})
print("Iterative Output (x, y values):")
print(df)

# Line chart showing Runge-Kutta method approximation


plt.figure(figsize=(8, 6))
plt.plot(x_vals, y_vals, label='Runge-Kutta Approximation', color='blue', marker='o')
plt.title("Runge-Kutta 4th Order Method - Line Chart")
plt.xlabel('x')
plt.ylabel('y')
plt.grid(True)
plt.legend()
plt.show()

# Mesh chart (3D plot of x, y)


fig = plt.figure(figsize=(10, 7))
ax = fig.add_subplot(111, projection='3d')
ax.plot_trisurf(x_vals, y_vals, np.zeros_like(x_vals), color='cyan')

# Labeling the axes


ax.set_title("Runge-Kutta 4th Order Method - Mesh Chart")
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('Zero Plane')

plt.show()
Iterative Output (x, y values):
x y
0 0.0 1.000000
1 0.1 1.110342
2 0.2 1.242805
3 0.3 1.399717
4 0.4 1.583648
5 0.5 1.797441
6 0.6 2.044236
7 0.7 2.327503
8 0.8 2.651079
9 0.9 3.019203
10 1.0 3.436559
11 1.1 3.908327
12 1.2 4.440228
13 1.3 5.038586
14 1.4 5.710391
15 1.5 6.463368
16 1.6 7.306053
17 1.7 8.247881
18 1.8 9.299278
19 1.9 10.471769
20 2.0 11.778090
Runge kutta 5th order

runge_kutta_5th_order: This function implements the fifth-order Runge-Kutta method to solve the ODE. The method calculates six slopes 𝑘 1 , 𝑘
2 , 𝑘 3 , 𝑘 4 , 𝑘 5 , k1,k2,k3,k4,k5, and 𝑘 6 k6 at each step. f: This function defines the differential equation 𝑑 𝑦 𝑑 𝑥 = 𝑥 + 𝑦 dx dy​=x+y.

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

# Runge-Kutta fifth-order method implementation


def runge_kutta_5th_order(f, x0, y0, h, x_end):
x_vals = [x0]
y_vals = [y0]

x = x0
y = y0

while x < x_end:


k1 = f(x, y)
k2 = f(x + h / 4, y + h * k1 / 4)
k3 = f(x + h / 4, y + h * k2 / 4)
k4 = f(x + h / 2, y + h * k3 / 2)
k5 = f(x + (3 * h) / 4, y + (3 * h * k4) / 4)
k6 = f(x + h, y + h * k5)

y = y + (h / 6) * (k1 + 4 * k4 + k5)
x = x + h

x_vals.append(x)
y_vals.append(y)

return np.array(x_vals), np.array(y_vals)

# Differential equation: dy/dx = x + y


def f(x, y):
return x + y

# Initial conditions and step size


x0 = 0
y0 = 1
h = 0.1
x_end = 2

# Apply Runge-Kutta 5th order method


x_vals, y_vals = runge_kutta_5th_order(f, x0, y0, h, x_end)

# Display iterative results in a table


df = pd.DataFrame({"x": x_vals, "y": y_vals})
print("Iterative Output (x, y values):")
print(df)

# Line chart showing Runge-Kutta method approximation


plt.figure(figsize=(8, 6))
plt.plot(x_vals, y_vals, label='Runge-Kutta Approximation', color='blue', marker='o')
plt.title("Runge-Kutta 5th Order Method - Line Chart")
plt.xlabel('x')
plt.ylabel('y')
plt.grid(True)
plt.legend()
plt.show()

# Mesh chart (3D plot of x, y)


fig = plt.figure(figsize=(10, 7))
ax = fig.add_subplot(111, projection='3d')
ax.plot_trisurf(x_vals, y_vals, np.zeros_like(x_vals), color='cyan')

# Labeling the axes


ax.set_title("Runge-Kutta 5th Order Method - Mesh Chart")
ax.set_xlabel
Iterative Output (x, y values):
x y
0 0.0 1.000000
1 0.1 1.109466
2 0.2 1.240869
3 0.3 1.396509
4 0.4 1.578922
5 0.5 1.790913
6 0.6 2.035579
7 0.7 2.316344
8 0.8 2.636987
9 0.9 3.001685
10 1.0 3.415053
11 1.1 3.882187
12 1.2 4.408718
13 1.3 5.000868
14 1.4 5.665509
15 1.5 6.410232
16 1.6 7.243426
17 1.7 8.174356
18 1.8 9.213259
19 1.9 10.371442
20 2.0 11.661398

matplotlib.axes._base._AxesBase.set_xlabel
def set_xlabel(xlabel, fontdict=None, labelpad=None, *, loc=None, **kwargs)

/usr/local/lib/python3.10/dist-packages/matplotlib/axes/_base.py
Set the label for the x-axis.

Parameters
----------
xlabel : str
h l b l t t
Double-click (or enter) to edit

Classical rungee kutta

The Classical Runge-Kutta method, commonly known as the fourth-order Runge-Kutta method, is widely used to solve ordinary differential
equations (ODEs) due to its balance between accuracy and computational efficiency. Below, I'll guide you through implementing the Classical
Runge-Kutta method in Google Colab.

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

# Classical Runge-Kutta method (4th order) implementation


def classical_runge_kutta(f, x0, y0, h, x_end):
x_vals = [x0]
y_vals = [y0]

x = x0
y = y0

while x < x_end:


k1 = f(x, y)
k2 = f(x + h / 2, y + h * k1 / 2)
k3 = f(x + h / 2, y + h * k2 / 2)
k4 = f(x + h, y + h * k3)

y = y + (h / 6) * (k1 + 2 * k2 + 2 * k3 + k4)
x = x + h

x_vals.append(x)
y_vals.append(y)

return np.array(x_vals), np.array(y_vals)

# Differential equation: dy/dx = x + y


def f(x, y):
return x + y

# Initial conditions and step size


x0 = 0
y0 = 1
h = 0.1
x_end = 2

# Apply Classical Runge-Kutta method


x_vals, y_vals = classical_runge_kutta(f, x0, y0, h, x_end)

# Display iterative results in a table


df = pd.DataFrame({"x": x_vals, "y": y_vals})
print("Iterative Output (x, y values):")
print(df)

# Line chart showing Runge-Kutta method approximation


plt.figure(figsize=(8, 6))
plt.plot(x_vals, y_vals, label='Runge-Kutta Approximation', color='blue', marker='o')
plt.title("Classical Runge-Kutta Method (4th Order) - Line Chart")
plt.xlabel('x')
plt.ylabel('y')
plt.grid(True)
plt.legend()
plt.show()

# Mesh chart (3D plot of x, y)


fig = plt.figure(figsize=(10, 7))
ax = fig.add_subplot(111, projection='3d')
ax.plot_trisurf(x_vals, y_vals, np.zeros_like(x_vals), color='cyan')

# Labeling the axes


ax.set_title("Classical Runge-Kutta Method (4th Order) - Mesh Chart")
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('Zero Plane')

plt.show()
Iterative Output (x, y values):
x y
0 0.0 1.000000
1 0.1 1.110342
2 0.2 1.242805
3 0.3 1.399717
4 0.4 1.583648
5 0.5 1.797441
6 0.6 2.044236
7 0.7 2.327503
8 0.8 2.651079
9 0.9 3.019203
10 1.0 3.436559
11 1.1 3.908327
12 1.2 4.440228
13 1.3 5.038586
14 1.4 5.710391
15 1.5 6.463368
16 1.6 7.306053
17 1.7 8.247881
18 1.8 9.299278
19 1.9 10.471769
20 2.0 11.778090
solve higher order ode with classical runge kutta method

Let's consider the second-order differential equation:

𝑑 2 𝑦 𝑑 𝑥 2 = − 𝑦 dx 2

d 2 y​=−y This can be converted into a system of first-order equations:

Let 𝑦 1 = 𝑦 y 1​=y Let 𝑦 2 = 𝑑 𝑦 𝑑 𝑥 y 2​= dx dy​

This gives us the following system:

𝑑 𝑦 1 𝑑 𝑥 = 𝑦 2 dx dy 1​

​=y 2​

𝑑 𝑦 2 𝑑 𝑥 = − 𝑦 1 dx dy 2​

​=−y 1​

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

# Classical Runge-Kutta method (4th order) implementation


def classical_runge_kutta_system(f, x0, y0, h, x_end):
x_vals = [x0]
y_vals = [y0[0]] # y1 values
y2_vals = [y0[1]] # y2 values

x = x0
y1 = y0[0]
y2 = y0[1]

while x < x_end:


k1 = f(x, [y1, y2])
k2 = f(x + h / 2, [y1 + h * k1[0] / 2, y2 + h * k1[1] / 2])
k3 = f(x + h / 2, [y1 + h * k2[0] / 2, y2 + h * k2[1] / 2])
k4 = f(x + h, [y1 + h * k3[0], y2 + h * k3[1]])

y1 += (h / 6) * (k1[0] + 2 * k2[0] + 2 * k3[0] + k4[0])


y2 += (h / 6) * (k1[1] + 2 * k2[1] + 2 * k3[1] + k4[1])
x += h

x_vals.append(x)
y_vals.append(y1)
y2_vals.append(y2)

return np.array(x_vals), np.array(y_vals), np.array(y2_vals)

# System of equations: dy1/dx = y2, dy2/dx = -y1


def f(x, y):
y1, y2 = y
return np.array([y2, -y1])

# Initial conditions and step size


x0 = 0
y0 = [1, 0] # y(0) = 1, dy/dx(0) = 0
h = 0.1
x_end = 10

# Apply Classical Runge-Kutta method to the system


x_vals, y1_vals, y2_vals = classical_runge_kutta_system(f, x0, y0, h, x_end)

# Display iterative results in a table


df = pd.DataFrame({"x": x_vals, "y1": y1_vals, "y2": y2_vals})
print("Iterative Output (x, y1, y2 values):")
print(df)

# Line chart showing Runge-Kutta method approximation for y1


plt.figure(figsize=(10, 6))
plt plot(x vals y1 vals label 'y1 (Position)' color 'blue' marker 'o')
plt.plot(x_vals, y1_vals, label= y1 (Position) , color= blue , marker= o )
plt.plot(x_vals, y2_vals, label='y2 (Velocity)', color='red', marker='x')
plt.title("Classical Runge-Kutta Method - Line Chart")
plt.xlabel('x')
plt.ylabel('y')
plt.grid(True)
plt.legend()
plt.show()

# Mesh chart (3D plot of x, y1, y2)


fig = plt.figure(figsize=(10, 7))
ax = fig.add_subplot(111, projection='3d')
ax.plot_trisurf(x_vals, y1_vals, y2_vals, color='cyan', alpha=0.6)

# Labeling the axes


ax.set_title("Classical Runge-Kutta Method - Mesh Chart")
ax.set_xlabel('x')
ax.set_ylabel('y1 (Position)')
ax.set_zlabel('y2 (Velocity)')

plt.show()
Iterative Output (x, y1, y2 values):
x y1 y2
0 0.0 1.000000 0.000000
1 0.1 0.995004 -0.099833
2 0.2 0.980067 -0.198669
3 0.3 0.955337 -0.295520
4 0.4 0.921061 -0.389418
.. ... ... ...
97 9.7 -0.962366 0.271753
98 9.8 -0.930429 0.366471
99 9.9 -0.889194 0.457528
100 10.0 -0.839075 0.544014
101 10.1 -0.780573 0.625064

[102 rows x 3 columns]

third order ode with fifth order runge kutta method


To solve a third-order ordinary differential equation (ODE) using the fifth-order Runge-Kutta method in Google Colab, we first convert the third-
order ODE into a system of first-order ODEs.

Example Problem Let's consider the third-order differential equation:

𝑑 3 𝑦 𝑑 𝑥 3 = − 𝑦 dx 3

d 3 y​=−y We can convert this into a system of first-order equations by introducing two new variables:

Let 𝑦 1 = 𝑦 y 1​=y Let 𝑦 2 = 𝑑 𝑦 𝑑 𝑥 y 2​= dx dy​

Let 𝑦 3 = 𝑑 2 𝑦 𝑑 𝑥 2 y 3​= dx 2

d 2 y​

This gives us the following system of equations:

𝑑 𝑦 1 𝑑 𝑥 = 𝑦 2 dx dy 1​

​=y 2​

𝑑 𝑦 2 𝑑 𝑥 = 𝑦 3 dx dy 2​

​=y 3​

𝑑 𝑦 3 𝑑 𝑥 = − 𝑦 1 dx dy 3​

​=−y 1

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from mpl_toolkits.mplot3d import Axes3D

# Fifth-Order Runge-Kutta method implementation


def runge_kutta_5th_order_system(f, x0, y0, h, x_end):
x_vals = [x0]
y1_vals = [y0[0]] # y1 values
y2_vals = [y0[1]] # y2 values
y3_vals = [y0[2]] # y3 values

x = x0
y1 = y0[0]
y2 = y0[1]
y3 = y0[2]

while x < x_end:


k1 = f(x, [y1, y2, y3])
k2 = f(x + h / 4, [y1 + h * k1[0] / 4, y2 + h * k1[1] / 4, y3 + h * k1[2] / 4])
k3 = f(x + h / 4, [y1 + h * k2[0] / 4, y2 + h * k2[1] / 4, y3 + h * k2[2] / 4])
k4 = f(x + h / 2, [y1 + h * k3[0] / 2, y2 + h * k3[1] / 2, y3 + h * k3[2] / 2])
k5 = f(x + (3 * h) / 4, [y1 + (3 * h * k4[0]) / 4, y2 + (3 * h * k4[1]) / 4, y3 + (3 * h * k4[2]) / 4])
k6 = f(x + h, [y1 + h * k5[0], y2 + h * k5[1], y3 + h * k5[2]])

y1 += (h / 6) * (k1[0] + 4 * k4[0] + k5[0])


y2 += (h / 6) * (k1[1] + 4 * k4[1] + k5[1])
y3 += (h / 6) * (k1[2] + 4 * k4[2] + k5[2])
x += h

x_vals.append(x)
y1_vals.append(y1)
y2_vals.append(y2)
y3_vals.append(y3)

return np.array(x_vals), np.array(y1_vals), np.array(y2_vals), np.array(y3_vals)

# System of equations: dy1/dx = y2, dy2/dx = y3, dy3/dx = -y1


def f(x, y):
y1, y2, y3 = y
return np.array([y2, y3, -y1])

# Initial conditions and step size


x0 = 0
y0 = [1, 0, 0] # y(0) = 1, dy/dx(0) = 0, d^2y/dx^2(0) = 0
h = 0.1
x_end = 10
# Apply the fifth-order Runge-Kutta method to the system
x_vals, y1_vals, y2_vals, y3_vals = runge_kutta_5th_order_system(f, x0, y0, h, x_end)

# Display iterative results in a table


df = pd.DataFrame({"x": x_vals, "y1": y1_vals, "y2": y2_vals, "y3": y3_vals})
print("Iterative Output (x, y1, y2, y3 values):")
print(df)

# Line chart showing Runge-Kutta method approximation for y1, y2, and y3
plt.figure(figsize=(10, 6))
plt.plot(x_vals, y1_vals, label='y1 (Position)', color='blue', marker='o')
plt.plot(x_vals, y2_vals, label='y2 (Velocity)', color='red', marker='x')
plt.plot(x_vals, y3_vals, label='y3 (Acceleration)', color='green', marker='s')
plt.title("Fifth-Order Runge-Kutta Method - Line Chart")
plt.xlabel('x')
plt.ylabel('y')
plt.grid(True)
plt.legend()
plt.show()

# Mesh chart (3D plot of x, y1, y2)


fig = plt.figure(figsize=(10, 7))
ax = fig.add_subplot(111, projection='3d')
ax.plot_trisurf(x_vals, y1_vals, y2_vals, color='cyan', alpha=0.6)

# Labeling the axes


ax.set_title("Fifth-Order Runge-Kutta Method - Mesh Chart")
ax.set_xlabel('x')
ax.set_ylabel('y1 (Position)')
ax.set_zlabel('y2 (Velocity)')

plt.show()

# Violin chart to visualize the distribution of y1, y2, and y3


plt.figure(figsize=(10, 6))
sns.violinplot(data=[y1_vals, y2_vals, y3_vals], inner="quartile")
plt.title("Distribution of y1, y2, and y3 Values")
plt.xticks(ticks=[0, 1, 2], labels=['y1 (Position)', 'y2 (Velocity)', 'y3 (Acceleration)'])
plt.ylabel('Value')
plt.xlabel('Variables')
plt.show()

Iterative Output (x, y1, y2, y3 values):


x y1 y2 y3
0 0.0 1.000000 0.000000 0.000000
1 0.1 0.999854 -0.004583 -0.099996

You might also like