-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQ1.py
More file actions
73 lines (54 loc) · 1.86 KB
/
Q1.py
File metadata and controls
73 lines (54 loc) · 1.86 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
"""
111901030
Mayank Singla
Coding Assignment 4 - Q1
"""
# %%
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 actual derivative (f'(x)) and forward finite difference approximation of the input function in the input interval
"""
def forward_finite_difference(x):
"""
Returns the forward finite difference approximation of the input function at x
"""
return (func(x + h) - func(x)) / h
# Number of points to plot
numPoints = 1000
# x-points generated uniformly between the interval
xpts = linspace(x_min, x_max, numPoints)
# The actual derivative of the input function at x-points
ypts_actual = [func_derivative(x) for x in xpts]
# The forward finite difference approximation of the input function at x-points
ypts_approx = [forward_finite_difference(x) for x in xpts]
# Plot the curves
# Giving title and labels to the plot
plt.title(
f"Visualization of actual derivative f'(x) and\nforward finite difference approximation δ⁺ of {func_str}"
)
plt.xlabel("x")
plt.ylabel("f'(x) and δ⁺")
# Plotting the actual derivative
plt.plot(xpts, ypts_actual, c="r", label="f'(x)")
# Plotting the forward finite difference approximation
plt.plot(xpts, ypts_approx, c="b", label="δ⁺")
# 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)