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

ppt code

The document outlines the application of Theorem 2.1 to determine the number of iterations required to approximate the root of the equation x³ - x - 1 = 0 within the interval [1, 2] to an accuracy of 10⁻⁴. It calculates that at least 14 iterations are necessary and provides a method for finding the root using the bisection method. Additionally, it includes various implementations of numerical methods such as Newton's method and Gaussian elimination for solving different equations.

Uploaded by

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

ppt code

The document outlines the application of Theorem 2.1 to determine the number of iterations required to approximate the root of the equation x³ - x - 1 = 0 within the interval [1, 2] to an accuracy of 10⁻⁴. It calculates that at least 14 iterations are necessary and provides a method for finding the root using the bisection method. Additionally, it includes various implementations of numerical methods such as Newton's method and Gaussian elimination for solving different equations.

Uploaded by

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

B15

Use Theorem 2.1 to find a bound for the number of iterations needed to achieve an
approximation with accuracy 10−4 to the solution of x3 −x−1 = 0 lying in the interval [1, 2].
Find an approximation to the root with this degree of accuracy

1. Given values:

• 𝑎=1a=1
• 𝑏=2b=2
• 𝜖=10−4ϵ=10−4

2. Using the formula:

𝑛≥log⁡(2−1)−log⁡(10−4)log⁡(2)=log⁡(1)−log⁡(10−4)log⁡(2)n
≥log(2)log(2−1)−log(10−4)=log(2)log(1)−log(10−4)

Since log⁡(1)=0log(1)=0, the formula simplifies to:

𝑛≥−log⁡(10−4)log⁡(2)=log⁡(104)log⁡(2)=4log⁡(10)log⁡(2)n≥l
og(2)−log(10−4)=log(2)log(104)=log(2)4log(10)

3. Substitute values:

• log⁡(10)≈2.302585log(10)≈2.302585
• log⁡(2)≈0.693147log(2)≈0.693147

4. Calculate:

𝑛≥4×2.3025850.693147≈9.210340.693147≈13.28n≥0.6931474×2.302
585≈0.6931479.21034≈13.28

Therefore, 𝑛≥14n≥14 (rounding up to the nearest whole number).

import math
# Given values
a = 1
b = 2
epsilon = 1e-4

# Calculate the number of iterations


n = math.ceil((math.log(b - a) - math.log(epsilon)) / math.log(2))
print(f"Number of iterations needed: {n}")
def f(x):
return x**3 - x - 1

def bisection_method(a, b, tol):


if f(a) * f(b) > 0:
raise ValueError("Function has the same sign at the ends of the
interval")

while (b - a) / 2 > tol:


midpoint = (a + b) / 2
if f(midpoint) == 0:
return midpoint # Found exact root
elif f(a) * f(midpoint) < 0:
b = midpoint
else:
a = midpoint
return (a + b) / 2

# Initial interval
a = 1
b = 2
tolerance = 1e-4

root = bisection_method(a, b, tolerance)


print(f"Root: {root}")
def f(x):
return x - 2**(-x)

def bisection_method(a, b, tol):


if f(a) * f(b) > 0:
raise ValueError("Function has the same sign at the ends of the
interval")

while (b - a) / 2 > tol:


midpoint = (a + b) / 2
if f(midpoint) == 0:
return midpoint # Found exact root
elif f(a) * f(midpoint) < 0:
b = midpoint
else:
a = midpoint
return (a + b) / 2

# Initial interval
a = 0
b = 1
tolerance = 1e-5
root_high_precision = bisection_method(a, b, tolerance)
print(f"Root: {root_high_precision}")

import math

def f(x):
return math.exp(x) - x**2 + 3*x - 2

def bisection_method(a, b, tol):


if f(a) * f(b) > 0:
raise ValueError("Function has the same sign at the ends of the
interval")

while (b - a) / 2 > tol:


midpoint = (a + b) / 2
if f(midpoint) == 0:
return midpoint # Found exact root
elif f(a) * f(midpoint) < 0:
b = midpoint
else:
a = midpoint
return (a + b) / 2

# Initial interval
a = 0
b = 1
tolerance = 1e-5

root = bisection_method(a, b, tolerance)


print(f"Root: {root}")

import math

def f(x):
return 2 * x * math.cos(2 * x) - (x + 1) ** 2

def bisection_method(a, b, tol):


if f(a) * f(b) > 0:
raise ValueError("Function has the same sign at the ends of the
interval")

while (b - a) / 2 > tol:


midpoint = (a + b) / 2
if f(midpoint) == 0:
return midpoint # Found exact root
elif f(a) * f(midpoint) < 0:
b = midpoint
else:
a = midpoint
return (a + b) / 2

# Intervals
intervals = [(-3, -2), (-1, 0)]
tolerance = 1e-5

roots = []
for a, b in intervals:
root = bisection_method(a, b, tolerance)
roots.append(root)
print(f"Root in interval [{a}, {b}]: {root}")

roots
import math

def f(x):
return x * math.cos(x) - 2 * x**2 + 3 * x - 1

def bisection_method(a, b, tol):


if f(a) * f(b) > 0:
raise ValueError("Function has the same sign at the ends of the
interval")

while (b - a) / 2 > tol:


midpoint = (a + b) / 2
if f(midpoint) == 0:
return midpoint # Found exact root
elif f(a) * f(midpoint) < 0:
b = midpoint
else:
a = midpoint
return (a + b) / 2

# Intervals
intervals = [(0.2, 0.3), (1.2, 1.3)]
tolerance = 1e-5

roots = []
for a, b in intervals:
root = bisection_method(a, b, tolerance)
roots.append(root)
print(f"Root in interval [{a}, {b}]: {root}")

roots

def g(x):
return (3 * x**2 + 3)**0.25

def fixed_point_iteration(p0, tol, max_iter=1000):


p = p0
for i in range(max_iter):
p_next = g(p)
if abs(p_next - p) < tol:
return p_next
p = p_next
return p # Return the last computed value if max iterations are reached

# Initial guess
p0 = 1
tolerance = 1e-2

solution = fixed_point_iteration(p0, tolerance)


print(f"Solution: {solution}")

import math
def g(x):
return (1 / math.pi) * (math.asin((-1 / 2) * x) + 2 * math.pi)

def fixed_point_iteration(p0, tol, max_iter=1000):


p = p0
for i in range(max_iter):
p_next = g(p)
if abs(p_next - p) < tol:
return p_next
p = p_next
return p # Return the last computed value if max iterations are reached

# Initial guess
p0 = 1
tolerance = 1e-2

solution = fixed_point_iteration(p0, tolerance)


print(f"Solution: {solution}")

def f(x):
return x**3 - 2*x**2 - 5

def df(x):
return 3*x**2 - 4*x

def newton_method(x0, tolerance):


while True:
x1 = x0 - f(x0) / df(x0)
if abs(x1 - x0) < tolerance:
return x1
x0 = x1

# Initial guess and tolerance


x0 = 4
tolerance = 1e-4

# Find the root


root = newton_method(x0, tolerance)
print("Root found using Newton's method:", root)

def f(x):
return x**3 + 3*x**2 - 1

def df(x):
return 3*x**2 + 6*x

def newton_method(x0, tolerance):


while True:
x1 = x0 - f(x0) / df(x0)
if abs(x1 - x0) < tolerance:
return x1
x0 = x1

# Initial guess and tolerance


x0 = -3
tolerance = 1e-4

# Find the root


root = newton_method(x0, tolerance)
print("Root found using Newton's method:", root)
import math

def f(x):
return x - math.cos(x)
def df(x):
return 1 + math.sin(x)

def newton_method(x0, tolerance):


while True:
x1 = x0 - f(x0) / df(x0)
if abs(x1 - x0) < tolerance:
return x1
x0 = x1

# Initial guess and tolerance


x0 = math.pi / 4
tolerance = 1e-4

# Find the root


root = newton_method(x0, tolerance)
print("Root found using Newton's method:", root)

import math

def f(x):
return x - 0.8 - 0.2 * math.sin(x)

def df(x):
return 1 - 0.2 * math.cos(x)

def newton_method(x0, tolerance):


while True:
x1 = x0 - f(x0) / df(x0)
if abs(x1 - x0) < tolerance:
return x1
x0 = x1

# Initial guess and tolerance


x0 = math.pi / 4
tolerance = 1e-4

# Find the root


root = newton_method(x0, tolerance)
print("Root found using Newton's method:", root)

math.log(x,base) default la e

import numpy as np

def g_elim(A, b):


n = len(A)

E = np.zeros([n, n+1], dtype=float)


for i in range(n):
E[i, :-1] = A[i, :]
E[i, n] = b[i]

x = np.zeros(n)

for i in range(n):
T = [j for j in E[i:,i] if j !=0]
if len(T) == 0:
print("No unique solution")
return
p = i + list(E[i:,i]).index(T[0])
if p != i:
print("E", p, "<-> E", i)
E[[i, p]] = E[[p, i]]
print(E, "\n")
for j in range(i+1, n):
m = E[j, i]/E[i, i]
print("m=", m)
E[j, :] = E[j, :] - m*E[i, :]
print(E, "\n")

if E[n-1, n-1] == 0:
print("No solution exists")
return
x[n-1] = E[n-1, n]/E[n-1, n-1]
for i in reversed(range(n-1)):
x[i] = (E[i, n] - sum([E[i, j]*x[j] for j in range(i,
n)]))/E[i, i]
print("solution :", x)

##### problem (a) #######


A = np.array([[1, -1, 3], [3, -3, 1], [1, 1, 0]], dtype=float)
b = np.array([[2], [-1], [3]], dtype = float)
g_elim(A, b)

##### problem (b) #######


A = np.array([[2, -1.5, 3], [-1, 0, 2], [4, -4.5, 5]],
dtype=float)
b = np.array([[1], [3], [1]], dtype = float)
g_elim(A, b)

##### problem (c) #######


A = np.array([[2, 0, 0, 0],
[1, 1.5, 0, 0],
[0,-3, 0.5, 0],
[2, -2, 1, 1]], dtype=float)
b = np.array([[3], [4.5], [-6.6], [0.8]], dtype = float)
g_elim(A, b)

##### problem (d) #######


A = np.array([[1, 1, 0, 1],
[2, 1, -1, 1],
[4, -1, -2, 2],
[3, -1, -1, 2]], dtype=float)
b = np.array([[2], [1], [0], [-3]], dtype = float)
g_elim(A, b)
import numpy as np
import re

def rnd(n, k):


if n == 0: return 0
s = re.search(r'.*e([+|-]){1}([0-9]*)',
format(n, "."+ str(k) + "e"))
if s.group(1) == "-": e = -1*int(s.group(2))
else : e = int(s.group(2))
n = n + 5*10**(e - (k+1))
return float(format(n, "."+ str(k-1) + "e"))

def rnd_v(v, k):


return np.array([rnd(j, k) for j in v])

def g_back_subs(A, b):


n = len(A)

E = np.zeros([n, n+1], dtype=float)


for i in range(n):
E[i, :-1] = A[i, :]
E[i, n] = b[i]

x = np.zeros(n)

for i in range(n):
T = [j for j in E[i:,i] if j !=0]
if len(T) == 0:
print("No unique solution")
return
p = i + list(E[i:,i]).index(T[0])
if p != i:
print("E", p, "<-> E", i)
E[[i, p]] = E[[p, i]]
for j in range(i+1, n):
m = rnd(E[j, i]/E[i, i], 2)
print("m=", m)
temp = rnd_v(m*E[i, :], 2)
E[j, :] = rnd_v(E[j, :] - temp, 2)
print(E, "\n")

if E[n-1, n-1] == 0:
print("No solution exists")
return
x[n-1] = rnd(E[n-1, n]/E[n-1, n-1], 2)
for i in reversed(range(n-1)):
temp = [rnd(E[i, j]*x[j], 2) for j in range(i, n)]
temp = rnd(sum(temp), 2)
temp = rnd(E[i, n] - temp, 2)
x[i] = rnd(temp/E[i, i],2)
print(x)
# problem (a)
A = np.array([[4, -1, 1], [2, 5, 2], [1, 2, 4]], dtype=float)
b = np.array([[8], [3], [11]], dtype = float)
g_back_subs(A, b)

# problem (b)
A = np.array([[4, 1, 2], [2, 4, -1], [1, 1, -3]], dtype=float)
b = np.array([[9], [-5], [-9]], dtype = float)
g_back_subs(A, b)
import numpy as np

def doolittle(A, b):


n = len(A)
L = np.zeros((n, n))
U = np.zeros((n, n))

# Step 1: Initialize L as an identity matrix and U as a zero matrix


for i in range(n):
L[i, i] = 1

# Step 2: Fill in the elements of U and L


for j in range(n):
U[j, j] = A[j, j] - np.dot(L[j, :j], U[:j, j])

for i in range(j+1, n):


L[i, j] = (A[i, j] - np.dot(L[i, :j], U[:j, j])) / U[j, j]

for i in range(j, n):


U[j, i] = A[j, i] - np.dot(L[j, :j], U[:j, i])

# Step 3: Solve the system of equations using forward and backward


substitution
y = np.zeros(n)
x = np.zeros(n)

# Forward substitution
for i in range(n):
y[i] = b[i] - np.dot(L[i, :i], y[:i])

# Backward substitution
for i in range(n-1, -1, -1):
x[i] = (y[i] - np.dot(U[i, i+1:], x[i+1:])) / U[i, i]

return x

# Coefficient matrix A
A = np.array([[3, 9, 6],
[18, 48, 39],
[9, -27, 42]])

# Right-hand side vector b


b = np.array([4.6, 27.2, 9.0])

# Solve the system using Doolittle's method


solution = doolittle(A, b)
print("Solution using Doolittle's method:", solution)
import numpy as np

# Define the Gauss-Seidel method


def gauss_seidel(A, b, x0, iterations):
n = len(b)
x = x0.copy()

for _ in range(iterations):
for i in range(n):
sum_ax = sum(A[i][j] * x[j] for j in range(n) if j != i)
x[i] = (b[i] - sum_ax) / A[i][i]

return x

# System of equations
A = np.array([[10, 1, 1],
[1, 10, 1],
[1, 1, 10]])
b = np.array([6, 6, 6])

# Initial guess
x0 = np.array([1, 1, 1], dtype=float)

# Number of iterations
iterations = 5

# Solve using Gauss-Seidel method


solution = gauss_seidel(A, b, x0, iterations)
print(solution

import numpy as np

# Define the Gauss-Seidel method with 6 significant figures


def gauss_seidel_6s(A, b, x0, iterations):
n = len(b)
x = x0.copy()

for _ in range(iterations):
for i in range(n):
sum_ax = sum(A[i][j] * x[j] for j in range(n) if j != i)
x[i] = round((b[i] - sum_ax) / A[i][i], 6)

return x

# System of equations
A = np.array([[10, 1, 1],
[1, 10, 1],
[1, 1, 10]])
b = np.array([6, 6, 6])

# Initial guess
x0 = np.array([1, 1, 1], dtype=float)

# Number of iterations
iterations = 5

# Solve using Gauss-Seidel method with 6 significant figures


solution_6s = gauss_seidel_6s(A, b, x0, iterations)
print(solution_6s)

import numpy as np

# Define the Jacobi method with 6 significant figures


def jacobi_6s(A, b, x0, iterations):
n = len(b)
x = x0.copy()
x_new = np.zeros_like(x)

for _ in range(iterations):
for i in range(n):
sum_ax = sum(A[i][j] * x[j] for j in range(n) if j != i)
x_new[i] = round((b[i] - sum_ax) / A[i][i], 6)
x = x_new.copy()

return x

# System of equations
A = np.array([[5, 1, 2],
[1, 4, -2],
[2, 3, 8]])
b = np.array([19, -2, 39])

# Initial guess
x0 = np.array([1, 1, 1], dtype=float)

# Number of iterations
iterations = 5

# Solve using Jacobi method with 6 significant figures


solution_6s = jacobi_6s(A, b, x0, iterations)
print(solution_6s)
import numpy as np

def lagrange_interpolating_polynomial(x_values, y_values, x):


n = len(x_values)
result = 0
for i in range(n):
term = y_values[i]
for j in range(n):
if j != i:
term *= (x - x_values[j]) / (x_values[i] - x_values[j])
result += term
return result

# Given data points


x_values = np.array([8.1, 8.3, 8.6, 8.7])
y_values = np.array([16.94410, 17.56492, 18.50515, 18.82091])

# Value to interpolate
x = 8.4

# Degree 1 interpolation
x_values_deg1 = x_values[:2]
y_values_deg1 = y_values[:2]
f_approx_deg1 = lagrange_interpolating_polynomial(x_values_deg1,
y_values_deg1, x)

# Degree 2 interpolation
x_values_deg2 = x_values[:3]
y_values_deg2 = y_values[:3]
f_approx_deg2 = lagrange_interpolating_polynomial(x_values_deg2,
y_values_deg2, x)

# Degree 3 interpolation
f_approx_deg3 = lagrange_interpolating_polynomial(x_values, y_values, x)

f_approx_deg1, f_approx_deg2, f_approx_deg3

b. f −1 3 if f (−0.75) = −0.07181250, f (−0.5) = −0.02475000, f (−0.25) = 0.33493750, f (0) =


1.10100000

c. f (0.25) if f (0.1) = 0.62049958, f (0.2) = −0.28398668, f (0.3) = 0.00660095, f (0.4) = 0.24842440


d. f (0.9) if f (0.6) = −0.17694460, f (0.7) = 0.01375227, f (0.8) = 0.22363362, f (1.0) = 0.65809197

import numpy as np

# Function to create the backward difference table


def backward_difference_table(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-1, j-2, -1):
diff_table[i][j] = diff_table[i][j-1] - diff_table[i-1][j-
1]
return diff_table

# Function to compute the Newton backward polynomial


def newton_backward_polynomial(x, y, x_to_approx, degree):
n = len(x)
diff_table = backward_difference_table(x, y)
h = x[1] - x[0]
u = (x_to_approx - x[-1]) / h
approx_value = y[-1]
u_product = 1
for i in range(1, degree + 1):
u_product *= (u + i - 1) / i
approx_value += u_product * diff_table[-1][i]
return round(approx_value, 6)

# Part a: Approximate f(-1/3)


x_values_a = np.array([-0.75, -0.5, -0.25, 0])
y_values_a = np.array([-0.07181250, -0.02475000, 0.33493750,
1.10100000])
x_to_approx_a = -1/3

# Degree 1 interpolation
approx_a_deg1 = newton_backward_polynomial(x_values_a, y_values_a,
x_to_approx_a, 1)
# Degree 2 interpolation
approx_a_deg2 = newton_backward_polynomial(x_values_a, y_values_a,
x_to_approx_a, 2)
# Degree 3 interpolation
approx_a_deg3 = newton_backward_polynomial(x_values_a, y_values_a,
x_to_approx_a, 3)

# Part b: Approximate f(0.25)


x_values_b = np.array([0.1, 0.2, 0.3, 0.4])
y_values_b = np.array([-0.62049958, -0.28398668, 0.00660095,
0.24842440])
x_to_approx_b = 0.25

# Degree 1 interpolation
approx_b_deg1 = newton_backward_polynomial(x_values_b, y_values_b,
x_to_approx_b, 1)
# Degree 2 interpolation
approx_b_deg2 = newton_backward_polynomial(x_values_b, y_values_b,
x_to_approx_b, 2)
# Degree 3 interpolation
approx_b_deg3 = newton_backward_polynomial(x_values_b, y_values_b,
x_to_approx_b, 3)

approx_a_deg1, approx_a_deg2, approx_a_deg3, approx_b_deg1,


approx_b_deg2, approx_b_deg3
import numpy as np
import matplotlib.pyplot as plt
# Given data
xi = np.array([4.0, 4.2, 4.5, 4.7, 5.1, 5.5, 5.9, 6.3, 6.8, 7.1])
yi = np.array([102.56, 113.18, 130.11, 142.05, 167.53, 195.14, 224.87,
256.73, 299.50, 326.72])

# Fit a polynomial of degree 1


coefficients = np.polyfit(xi, yi, 1)

# Compute the fitted values


yi_fit = np.polyval(coefficients, xi)

# Calculate the Sum of Squared Errors (SSE)


sse = np.sum((yi - yi_fit) ** 2)
print("Sum of Squared Errors:", sse)

# Plot the data and the fitted line


plt.scatter(xi, yi, color='blue', label='Data points')
plt.plot(xi, yi_fit, color='red', label='Fitted line')
plt.xlabel('xi')
plt.ylabel('yi')
plt.legend()
plt.title(f"Linear Fit: y = {coefficients[0]:.2f}x +
{coefficients[1]:.2f}\nSSE: {sse:.2f}")
plt.show()

B15 xem trong giải

import numpy as np
import matplotlib.pyplot as plt

# Given data
xi = np.array([4.0, 4.2, 4.5, 4.7, 5.1, 5.5, 5.9, 6.3, 6.8, 7.1])
yi = np.array([102.56, 113.18, 130.11, 142.05, 167.53, 195.14, 224.87,
256.73, 299.50, 326.72])

# Fit a polynomial of degree 2


coefficients_deg2 = np.polyfit(xi, yi, 2)
yi_fit_deg2 = np.polyval(coefficients_deg2, xi)
sse_deg2 = np.sum((yi - yi_fit_deg2) ** 2)
print("Degree 2 coefficients:", coefficients_deg2)
print("Degree 2 SSE:", sse_deg2)

# Fit a polynomial of degree 3


coefficients_deg3 = np.polyfit(xi, yi, 3)
yi_fit_deg3 = np.polyval(coefficients_deg3, xi)
sse_deg3 = np.sum((yi - yi_fit_deg3) ** 2)
print("Degree 3 coefficients:", coefficients_deg3)
print("Degree 3 SSE:", sse_deg3)

# Plotting the data and the fitted lines


plt.scatter(xi, yi, color='blue', label='Data points')

# Plot the polynomial fits


plt.plot(xi, yi_fit_deg2, color='green', label='Degree 2 fit')
plt.plot(xi, yi_fit_deg3, color='purple', label='Degree 3 fit')

plt.xlabel('xi')
plt.ylabel('yi')
plt.legend()
plt.title('Least Squares Polynomial Fits')
plt.show()

import numpy as np
from scipy.stats import linregress

# Given data
xi = np.array([4.0, 4.2, 4.5, 4.7, 5.1, 5.5, 5.9, 6.3, 6.8, 7.1])
yi = np.array([102.56, 113.18, 130.11, 142.05, 167.53, 195.14, 224.87,
256.73, 299.50, 326.72])

# Calculate natural logarithm of yi


Y = np.log(yi)

# Perform linear regression


slope, intercept, _, _, _ = linregress(xi, Y)

# Compute a and b
a = slope
B = intercept
b = np.exp(B)

# Compute least squares approximation


def least_squares(x):
return b * np.exp(a * x)

# Compute the error


error = np.sum((yi - least_squares(xi)) ** 2)

print("a:", a)
print("b:", b)
print("Error:", error)
import numpy as np
from scipy.stats import linregress

# Given data
xi = np.array([4.0, 4.2, 4.5, 4.7, 5.1, 5.5, 5.9, 6.3, 6.8, 7.1])
yi = np.array([102.56, 113.18, 130.11, 142.05, 167.53, 195.14, 224.87,
256.73, 299.50, 326.72])

# Calculate logarithm of xi and yi


log_xi = np.log10(xi)
log_yi = np.log10(yi)

# Perform linear regression


slope, intercept, _, _, _ = linregress(log_xi, log_yi)

# Compute a and b
a = slope
B = intercept
b = 10 ** B

# Compute least squares approximation


def least_squares(x):
return b * (x ** a)

# Compute the error


error = np.sum((yi - least_squares(xi)) ** 2)

print("a:", a)
print("b:", b)
print("Error:", error)

def three_point_endpoint_formula(f_x0, f_x1, f_x2, h):


return (1 / (2 * h)) * (-3 * f_x0 + 4 * f_x1 - f_x2)

def three_point_midpoint_formula(f_x_minus_h, f_x, f_x_plus_h, h):


return (1 / (2 * h)) * (f_x_plus_h - f_x_minus_h) - (h**2 / 6) *
(f_x_plus_h - 2*f_x + f_x_minus_h)

# Given data
x_values = [1.1, 1.2, 1.3, 1.4]
f_values = [9.025013, 11.02318, 13.46374, 16.44465]
h = x_values[1] - x_values[0] # Assuming equally spaced points

# Calculate f'(1.4) using the three-point endpoint formula


f_prime_1_4 = three_point_endpoint_formula(f_values[0], f_values[1],
f_values[2], h)

# Calculate the missing entry at x = 1.4


missing_value_1_4_endpoint = three_point_endpoint_formula(f_values[3],
f_values[2], f_values[1], -h)

# Calculate the missing entries using the three-point midpoint formula


missing_value_1_2_midpoint = three_point_midpoint_formula(f_values[0],
f_values[1], f_values[2], h)
missing_value_1_3_midpoint = three_point_midpoint_formula(f_values[1],
f_values[2], f_values[3], h)

# Print the missing values


print(f"The missing value at x = 1.1 (Endpoint Formula) is
approximately: {f_prime_1_4}")
print(f"The missing value at x = 1.4 (Endpoint Formula) is
approximately: {missing_value_1_4_endpoint}")
print(f"The missing value at x = 1.2 (Midpoint Formula) is
approximately: {missing_value_1_2_midpoint}")
print(f"The missing value at x = 1.3 (Midpoint Formula) is
approximately: {missing_value_1_3_midpoint}")

from scipy.integrate import simps

# Define the integrand function


def integrand(x):
return x**4

# Define the integration limits


lower_limit = 0.5
upper_limit = 1

# Define the sample points


sample_points = [lower_limit, (lower_limit + upper_limit) / 2,
upper_limit]

# Compute the integral using Simpson's rule


result = simps([integrand(x) for x in sample_points], sample_points)

# Print the result


print("The approximate value of the integral using Simpson's rule is:",
result)
# Define the function to approximate the integral using the Trapezoidal rule

def trapezoidal_rule(f, a, b, n):

"""

Approximates the integral of f(x) from a to b using the Trapezoidal rule with n subintervals.

"""

# Calculate the width of each subinterval

h = (b - a) / n

# Initialize the sum

integral_sum = 0

# Compute the sum of the function values at the endpoints and the midpoint of each
subinterval

for i in range(n):

x0 = a + i * h

x1 = a + (i + 1) * h

integral_sum += (f(x0) + f(x1)) / 2 * h

return integral_sum

# Define the integrand function

def integrand(x):

return x**4

# Define the integration limits

lower_limit = 0.5

upper_limit = 1

# Define the number of subintervals

num_subintervals = 1000
# Approximate the integral using the Trapezoidal rule

result = trapezoidal_rule(integrand, lower_limit, upper_limit, num_subintervals)

# Print the result

print("The approximate value of the integral using the Trapezoidal rule is:", result)

# Define the function to approximate the integral using the Midpoint


rule
def midpoint_rule(f, a, b, n):
"""
Approximates the integral of f(x) from a to b using the Midpoint
rule with n subintervals.
"""
# Calculate the width of each subinterval
h = (b - a) / n

# Initialize the sum


integral_sum = 0

# Compute the sum of the function values at the midpoints of each


subinterval
for i in range(n):
midpoint = a + (i + 0.5) * h
integral_sum += f(midpoint) * h

return integral_sum

# Define the integrand function


def integrand(x):
return x**4

# Define the integration limits


lower_limit = 0.5
upper_limit = 1

# Define the number of subintervals


num_subintervals = 1000

# Approximate the integral using the Midpoint rule


result = midpoint_rule(integrand, lower_limit, upper_limit,
num_subintervals)

# Print the result


print("The approximate value of the integral using the Midpoint rule
is:", result)

from scipy.misc import derivative

# Define the integrand function


def integrand(x):
return x**4

# Define the integration limits


a = 0.5
b = 1

# Calculate the maximum value of the fourth derivative of the integrand


function
M = max(abs(derivative(integrand, a, n=4)), abs(derivative(integrand,
b, n=4)))

# Define the number of subintervals


n = 10 # Adjust the number of subintervals as needed

# Calculate the bound error for Simpson's rule


error_bound = ((b - a)**5 / (180 * n**4)) * M

# Print the result


print("The bound error for Simpson's rule is:", error_bound)

import numpy as np

# Define the quadrature formula


def quadrature_formula(f):
return f(-np.sqrt(3)/3) + f(np.sqrt(3)/3)

# Define a function to test the quadrature formula


def test_quadrature_formula(deg):
# Define a polynomial function of degree deg
def poly(x):
return x**deg

# Evaluate the integral of the polynomial function using the


quadrature formula
integral_approximation = quadrature_formula(poly)

# Compute the exact integral of the polynomial function


exact_integral = 2 / (deg + 1)

# Compute the error


error = abs(integral_approximation - exact_integral)

return error

# Test the quadrature formula with polynomials of degrees 0 to 5


for deg in range(6):
error = test_quadrature_formula(deg)
print(f"Degree {deg} polynomial: Error = {error}")

def euler_method(f, a, b, y0, h):


"""
Approximates the solution of the initial-value problem y' = f(t,
y), a <= t <= b, y(a) = y0 using Euler's method.
"""
# Initialize lists to store values of t and y
t_values = [a]
y_values = [y0]

# Initialize t and y
t = a
y = y0

# Perform Euler's method


while t < b:
# Update y using Euler's method
y += h * f(t, y)

# Update t
t += h

# Append new values to lists


t_values.append(t)
y_values.append(y)

return t_values, y_values

# Define the differential equation y' = f(t, y)


def f(t, y):
return y / t - (y / t)**2

# Define the initial conditions


a = 1
b = 2
y0 = 1

# Define the step size


h = 0.1

# Use Euler's method to approximate the solution


t_values, y_values = euler_method(f, a, b, y0, h)

# Print the results


print("t values:", t_values)
print("Approximate solution (y values):", y_values)

def taylors_method_order_two(f, df_dt, a, b, y0, h):


"""
Approximates the solution of the initial-value problem y' = f(t,
y), a <= t <= b, y(a) = y0 using Taylor's method of order two.
"""
# Initialize lists to store values of t and y
t_values = [a]
y_values = [y0]

# Initialize t and y
t = a
y = y0

# Perform Taylor's method


while t < b:
# Compute the next value of y using Taylor's method of order
two
y += h * f(t, y) + (h**2 / 2) * df_dt(t, y)

# Update t
t += h

# Append new values to lists


t_values.append(t)
y_values.append(y)

return t_values, y_values


# Define the differential equation y' = f(t, y)
def f(t, y):
return y / t - (y / t)**2

# Define the derivative of the differential equation with respect to t,


df/dt = f_t(t, y)
def f_t(t, y):
return (1 / t) - 2 * (y / t)**2

# Define the initial conditions


a = 1
b = 1.2
y0 = 1

# Define the step size


h = 0.1

# Use Taylor's method of order two to approximate the solution


t_values, y_values = taylors_method_order_two(f, f_t, a, b, y0, h)

# Print the results


print("t values:", t_values)
print("Approximate solution (y values):", y_values)

import sympy as sp

def taylors_method_order_two(f, df_dt, df_dy, a, b, y0, h):


"""
Approximates the solution of the initial-value problem y' = f(t,
y), a <= t <= b, y(a) = y0 using Taylor's method of order two.
"""
# Initialize lists to store values of t and y
t_values = [a]
y_values = [y0]

# Initialize t and y
t = a
y = y0

# Perform Taylor's method


while t < b:
# Compute the next value of y using Taylor's method of order
two
y += h * f(t, y) + (h**2 / 2) * (df_dt(t, y) + df_dy(t, y) *
f(t, y))

# Update t
t += h

# Append new values to lists


t_values.append(t)
y_values.append(y)

return t_values, y_values

# Define the differential equation y' = f(t, y)


t, y = sp.symbols('t y')
f_expr = y / t - (y / t)**2
f = sp.lambdify((t, y), f_expr)

# Tính đạo hàm của f theo t và y


df_dt_expr = sp.diff(f_expr, t)
df_dy_expr = sp.diff(f_expr, y)
df_dt = sp.lambdify((t, y), df_dt_expr)
df_dy = sp.lambdify((t, y), df_dy_expr)

# Define the initial conditions


a = 1
b = 1.2
y0 = 1

# Define the step size


h = 0.1

# Use Taylor's method of order two to approximate the solution


t_values, y_values = taylors_method_order_two(f, df_dt, df_dy, a, b,
y0, h)

# Print the results


print("t values:", t_values)
print("Approximate solution (y values):", y_values)

import sympy as sp

def taylors_method_order_three(f, df_dt, df_dy, d2f_dt2, d2f_dydt,


d2f_dy2, a, b, y0, h):
"""
Approximates the solution of the initial-value problem y' = f(t,
y), a <= t <= b, y(a) = y0 using Taylor's method of order three.
"""
# Initialize lists to store values of t and y
t_values = [a]
y_values = [y0]

# Initialize t and y
t = a
y = y0

# Perform Taylor's method


while t < b:
# Compute the next value of y using Taylor's method of order
three
y += h * f(t, y) + (h**2 / 2) * df_dt(t, y) + (h**3 / 6) *
d2f_dt2(t, y) + (h**3 / 6) * (df_dy(t, y) * f(t, y) + d2f_dydt(t, y) *
df_dt(t, y)) + (h**3 / 6) * d2f_dy2(t, y) * f(t, y)

# Update t
t += h

# Append new values to lists


t_values.append(t)
y_values.append(y)

return t_values, y_values

# Define the differential equation y' = f(t, y)


t, y = sp.symbols('t y')
f_expr = y / t - (y / t)**2
f = sp.lambdify((t, y), f_expr)

# Tính đạo hàm của f theo t và y


df_dt_expr = sp.diff(f_expr, t)
df_dy_expr = sp.diff(f_expr, y)
df_dt = sp.lambdify((t, y), df_dt_expr)
df_dy = sp.lambdify((t, y), df_dy_expr)

# Tính đạo hàm thứ hai của f theo t và y


d2f_dt2_expr = sp.diff(df_dt_expr, t)
d2f_dydt_expr = sp.diff(df_dt_expr, y)
d2f_dy2_expr = sp.diff(df_dy_expr, y)
d2f_dt2 = sp.lambdify((t, y), d2f_dt2_expr)
d2f_dydt = sp.lambdify((t, y), d2f_dydt_expr)
d2f_dy2 = sp.lambdify((t, y), d2f_dy2_expr)

# Define the initial conditions


a = 1
b = 1.2
y0 = 1

# Define the step size


h = 0.1

# Use Taylor's method of order three to approximate the solution


t_values, y_values = taylors_method_order_three(f, df_dt, df_dy,
d2f_dt2, d2f_dydt, d2f_dy2, a, b, y0, h)

# Print the results


print("t values:", t_values)
print("Approximate solution (y values):", y_values)

def modified_euler_method(f, a, b, alpha, h):


"""
Approximates the solution of the initial-value problem y' = f(t,
y), a <= t <= b, y(a) = alpha using Modified Euler's method.
"""
t_values = [a]
w_values = [alpha]
t = a
w = alpha
while t < b:
# Compute the slopes at the current point and the predicted
next point
slope_current = f(t, w)
slope_predicted = f(t + h, w + h * slope_current)

# Update w using Modified Euler's method formula


w_next = w + h / 2 * (slope_current + slope_predicted)

# Update t and w for the next iteration


t += h
w = w_next

# Append new values to lists


t_values.append(t)
w_values.append(w)
return t_values, w_values

# Example usage:
# Define the differential equation y' = f(t, y)
def f(t, y):
return t * sp.exp(3 * t) - 2 * y

# Define the initial conditions


a = 0
b = 1
alpha = 0
h = 0.5
# Use Modified Euler's method to approximate the solution
t_values, w_values = modified_euler_method(f, a, b, alpha, h)

# Print the results


print("t values:", t_values)
print("Approximate solution (w values):", w_values)

def midpoint_method(f, a, b, alpha, h):


"""
Approximates the solution of the initial-value problem y' = f(t,
y), a <= t <= b, y(a) = alpha using the Midpoint method.
"""
t_values = [a]
w_values = [alpha]
t = a
w = alpha
while t < b:
# Compute the slope at the current point
slope = f(t, w)

# Predict w at the midpoint of the interval


w_midpoint = w + h * slope / 2

# Compute the slope at the midpoint


slope_midpoint = f(t + h / 2, w_midpoint)

# Update w using the slope at the midpoint


w_next = w + h * slope_midpoint

# Update t and w for the next iteration


t += h
w = w_next

# Append new values to lists


t_values.append(t)
w_values.append(w)
return t_values, w_values

# Example usage:
# Define the differential equation y' = f(t, y)
def f(t, y):
return t * sp.exp(3 * t) - 2 * y

# Define the initial conditions


a = 0
b = 1
alpha = 0
h = 0.5

# Use the Midpoint method to approximate the solution


t_values, w_values = midpoint_method(f, a, b, alpha, h)

# Print the results


print("t values:", t_values)
print("Approximate solution (w values):", w_values)

def runge_kutta_order_four(f, a, b, y0, h):


"""
Approximates the solution of the initial-value problem y' = f(t,
y), a <= t <= b, y(a) = y0 using the Runge-Kutta method of order four.
"""
t_values = [a]
y_values = [y0]
t = a
y = y0
while t < b:
# Compute slopes at several points within the interval
k1 = h * f(t, y)
k2 = h * f(t + h/2, y + k1/2)
k3 = h * f(t + h/2, y + k2/2)
k4 = h * f(t + h, y + k3)

# Use a weighted average of these slopes to approximate the


change in y
y += (k1 + 2*k2 + 2*k3 + k4) / 6

# Update t
t += h

# Append new values to lists


t_values.append(t)
y_values.append(y)
return t_values, y_values

# Define the differential equation y' = f(t, y)


def f(t, y):
return y / t - (y / t)**2

# Define the actual solution


def actual_solution(t):
return t / (1 + sp.ln(t))

# Define the initial conditions


a = 1
b = 2
y0 = 1
h = 0.1

# Use the Runge-Kutta method of order four to approximate the solution


t_values, y_values = runge_kutta_order_four(f, a, b, y0, h)

# Calculate the actual solution


actual_y_values = [actual_solution(t) for t in t_values]

# Print the results


print("t values:", t_values)
print("Approximate solution (y values):", y_values)
print("Actual solution (y values):", actual_y_values)

def runge_kutta_order_four(f, t, w, h):


"""
Approximates w(t + h) using the Runge-Kutta method of order 4.
"""
k1 = h * f(t, w)
k2 = h * f(t + h/2, w + k1/2)
k3 = h * f(t + h/2, w + k2/2)
k4 = h * f(t + h, w + k3)
return w + (k1 + 2*k2 + 2*k3 + k4) / 6

def predictor_corrector_order_four(f, a, b, alpha, N):


"""
Approximates the solution of the initial-value problem y' = f(t,
y), a <= t <= b, y(a) = alpha using the Predictor-Corrector method of
order 4.
"""
h = (b - a) / N
t_values = [a]
w_values = [alpha]
t = a
w = alpha

# Perform initial steps using Runge-Kutta method of order 4


for i in range(1, 4):
w = runge_kutta_order_four(f, t, w, h)
t += h
t_values.append(t)
w_values.append(w)

# Perform Predictor-Corrector steps


while t < b:
# Predictor step
w_star = w + h / 24 * (55 * f(t, w) - 59 * f(t - h, w_values[-
2]) + 37 * f(t - 2*h, w_values[-3]) - 9 * f(t - 3*h, w_values[-4]))

# Corrector step
w_next = w + h / 24 * (9 * f(t + h, w_star) + 19 * f(t, w) - 5
* f(t - h, w_values[-2]) + f(t - 2*h, w_values[-3]))

# Update t and w for the next iteration


t += h
w = w_next

# Append new values to lists


t_values.append(t)
w_values.append(w)

return t_values, w_values

# Define the differential equation y' = f(t, y)


def f(t, y):
return t * sp.exp(3 * t) - 2 * y

# Define the initial conditions


a = 0
b = 1
alpha = 0
N = 5 # Number of steps

# Use the Predictor-Corrector method of order 4 to approximate the


solution
t_values, w_values = predictor_corrector_order_four(f, a, b, alpha, N)

# Print the results


print("t values:", t_values)
print("Approximate solution (w values):", w_values)

import numpy as np
from scipy.interpolate import CubicSpline

# Define the function


def f(x):
return x * np.log(x)

# Given data points


x_values = np.array([8.3, 8.6])
y_values =np.array([17.56492,18.50515])

# Construct cubic spline interpolant


cubic_spline = CubicSpline(x_values, y_values)

# Approximate f(8.4) and f'(8.4)


x_new = 8.4
f_8_4_approx = cubic_spline(x_new)
f_prime_8_4_approx = cubic_spline(x_new, 1) # 1 indicates first
derivative

# Calculate actual values


f_8_4_actual = f(x_new)
f_prime_8_4_actual = x_new / 8.4 + np.log(x_new)

# Calculate actual error


error_f = abs(f_8_4_actual - f_8_4_approx)
error_f_prime = abs(f_prime_8_4_actual - f_prime_8_4_approx)

print("Approximation of f(8.4):", f_8_4_approx)


print("Approximation of f'(8.4):", f_prime_8_4_approx)
print("Actual value of f(8.4):", f_8_4_actual)
print("Actual value of f'(8.4):", f_prime_8_4_actual)
print("Error in approximation of f(8.4):", error_f)
print("Error in approximation of f'(8.4):", error_f_prime)
np.sin(np.exp(x) - 2)

np.log(np.exp(x) + 2)

import numpy as np

from scipy.interpolate import CubicSpline

# Given data points

x_values = np.array([0, 1, 2])


y_values = np.array([0, 1, 2])

# Define the derivatives at the boundary

s_prime_0 = 1

s_prime_2 = 1

# Construct clamped cubic spline interpolant

cubic_spline = CubicSpline(x_values, y_values, bc_type=((1, s_prime_0), (1, s_prime_2)))

# Evaluate the spline at some points

x_eval = np.linspace(0, 2, 100)

y_eval = cubic_spline(x_eval)

# Print the coefficients of the spline

print("Coefficients of the spline:")

print(cubic_spline.c)

# Plot the interpolated spline

import matplotlib.pyplot as plt

plt.plot(x_eval, y_eval, label='Clamped Cubic Spline')

plt.scatter(x_values, y_values, color='red', label='Data Points')

plt.xlabel('x')

plt.ylabel('s(x)')

plt.title('Clamped Cubic Spline Interpolation')

plt.legend()

plt.grid(True)

plt.show()

You might also like