-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQ2.py
More file actions
97 lines (74 loc) · 2.77 KB
/
Q2.py
File metadata and controls
97 lines (74 loc) · 2.77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
"""
111901030
Mayank Singla
Coding Assignment 4 - Q2
"""
# %%
from math import sin, cos
from numpy import linspace
import matplotlib.pyplot as plt
def sin_x_2(x):
"""
Returns the value of the function sin(x²) at x
"""
return sin(x * x)
def sin_x_2_derivative(x):
"""
Returns the derivative of the function sin(x²) at x
Derivative is: 2 * x * cos(x²)
"""
return 2 * x * cos(x * x)
def visualize(func, func_derivative, func_str, h, x_min, x_max):
"""
Visualize the absolute errors of approximation of δ⁺, δ⁻, and δᶜ
"""
def forward_finite_difference(x):
"""
Returns the forward finite difference approximation of the input function at x
"""
return (func(x + h) - func(x)) / h
def backward_finite_difference(x):
"""
Returns the backward finite difference approximation of the input function at x
"""
return (func(x) - func(x - h)) / h
def centered_finite_difference(x):
"""
Returns the centered finite difference approximation of the input function at x
"""
return (func(x + h) - func(x - h)) / (2 * h)
# Number of points to plot
numPoints = 1000
# x-points generated uniformly between the interval
xpts = linspace(x_min, x_max, numPoints)
# The forward finite difference approximation of the input function at x-points
ypts_forward = [
abs(forward_finite_difference(x) - func_derivative(x)) for x in xpts
]
# The backward finite difference approximation of the input function at x-points
ypts_backward = [
abs(backward_finite_difference(x) - func_derivative(x)) for x in xpts
]
# The centered finite difference approximation of the input function at x-points
ypts_centered = [
abs(centered_finite_difference(x) - func_derivative(x)) for x in xpts
]
# Plot the curves
# Giving title and labels to the plot
plt.title(
f"Visualization of absolute errors of approximation\nof δ⁺(x), δ⁻(x) and δᶜ(x) of {func_str}"
)
plt.xlabel("x")
plt.ylabel("Absolute error")
# Plotting the absolute errors of approximation for forward finite difference approximation
plt.plot(xpts, ypts_forward, c="r", label="|δ⁺ - f'(x)|")
# Plotting the absolute errors of approximation for backward finite difference approximation
plt.plot(xpts, ypts_backward, c="b", label="|δ⁻ - f'(x)|")
# Plotting the absolute errors of approximation for centered finite difference approximation
plt.plot(xpts, ypts_centered, c="g", label="|δᶜ - f'(x)|")
# Displaying the curve
plt.grid()
plt.legend(loc="upper left")
plt.show()
if __name__ == "__main__":
visualize(sin_x_2, sin_x_2_derivative, "sin(x²)", 0.01, 0, 1)