Code Explanation:
1. Importing Libraries
import matplotlib.pyplot as plt
import numpy as np
matplotlib.pyplot → gives plotting functions (like plt.plot(), plt.show()).
numpy → used for numerical computations, arrays, math functions.
plt and np are just short aliases to make code shorter.
2. Create Evenly Spaced Values
x = np.linspace(0, np.pi, 5)
np.linspace(start, stop, num) creates num evenly spaced numbers between start and stop (inclusive).
Here:
start = 0
stop = np.pi (≈ 3.14159)
num = 5
So, x will be:
[0. 0.78539816 1.57079633 2.35619449 3.14159265]
(these are 0, π/4, π/2, 3π/4, π).
3. Apply the Sine Function
y = np.round(np.sin(x), 2)
np.sin(x) → takes the sine of each value in x.
sin(0) = 0
sin(π/4) ≈ 0.7071
sin(π/2) = 1
sin(3π/4) ≈ 0.7071
sin(π) = 0
So before rounding:
[0. 0.70710678 1. 0.70710678 0. ]
np.round(..., 2) → rounds each value to 2 decimal places:
[0. 0.71 1. 0.71 0. ]
4. Convert to List and Print
print(list(y))
y is a NumPy array.
list(y) converts it into a normal Python list.
Output:
[0.0, 0.71, 1.0, 0.71, 0.0]
✅ Final Output
[0.0, 0.71, 1.0, 0.71, 0.0]
Download Book - 500 Days Python Coding Challenges with Explanation
.png)

0 Comments:
Post a Comment