Python Assignment Unit 2
Python Assignment Unit 2
1.Plot a sine wave using markers +, o, and x using three different colors.
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Sine Wave with Different Markers and Colors')
plt.legend()
plt.grid(True)
plt.show()
2.Plot tan θ, for θ from −2π to 2π, watch for singular points
tan_theta = np.tan(theta)
plt.figure(figsize=(8, 4))
plt.plot(theta, tan_theta, label='tan(θ)', color='blue')
plt.scatter([-np.pi/2, np.pi/2, 3*np.pi/2], [np.inf, -np.inf, np.inf], color='red',
x=np.linspace(0,L,samples,endpoint=False)
y=triang(samples)
a0=2./L*simps(y,x)
an=lambda n:2.0/L*simps(y*np.cos(2.*np.pi*n*x/L),x)
bn=lambda n:2.0/L*simps(y*np.sin(2.*np.pi*n*x/L),x)
s=a0/2.+sum([an(k)*np.cos(2.*np.pi*k*x/L)+bn(k)*np.sin(2.*np.pi*k*x/L)
for k in range(1,terms+1)])
plt.plot(x,s,label="Fourier series")
plt.plot(x,y,label="Original Triangular wave")
plt.xlabel("$x$")
plt.ylabel("$y=f(x)$")
plt.legend(loc='best',prop={'size':10})
plt.title("Triangular wave signal analysis by Fouries series")
plt.savefig("fs_triangular.png")
plt.show()
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Cell In[18], line 19
14 bn=lambda n:2.0/L*simps(y*np.sin(2.*np.pi*n*x/L),x)
16 s=a0/2.+sum([an(k)*np.cos(2.*np.pi*k*x/L)+bn(k)*np.sin(2.*np.pi*k*x/L)
17 for k in range(1,terms+1)])
---> 19 plt.plot(x,s,label="Fourier series")
20 plt.plot(x,y,label="Original Triangular wave")
21 plt.xlabel("$x$")
ValueError: x and y must have same first dimension, but have shapes (50,) and (1,)
Write a Python program to calculate the sine function using series expansion and plot it.
plt.figure(figsize=(8, 4))
plt.plot(x, sine_values, label='Sine Function (Maclaurin Series)')
plt.xlabel('x')
plt.ylabel('sin(x)')
plt.title('Sine Function Plot Using Maclaurin Series')
plt.grid(True)
plt.axhline(y=0, color='black', linewidth=0.5)
plt.axvline(x=0, color='black', linewidth=0.5)
plt.legend()
plt.show()
pylab, with axes and title. Use red colored circles to mark the points.
x = linspace(0, 5, 20)
y = 5 * x**2 + 3 * x + 2
xlabel('x')
ylabel('y')
title('Plot of y = 5x^2 + 3x + 2')
grid(True)
legend()
show()
Write a program to plot r = cos(kθ) in polar coordinates for θ from 0 to 10π, k is an integer.
Write for two different values of k (even and odd).
k_even = 2
k_odd = 3
plt.subplot(121, projection='polar')
plt.plot(theta, r_even, label=f'r = cos({k_even}θ)', color='blue')
plt.title(f'r = cos({k_even}θ) in Polar Coordinates')
plt.legend()
plt.subplot(122, projection='polar')
plt.plot(theta, r_odd, label=f'r = cos({k_odd}θ)', color='green')
plt.title(f'r = cos({k_odd}θ) in Polar Coordinates')
plt.legend()
plt.tight_layout()
plt.show()
Write a Python program to plot a square wave using the Fourier series, number of terms
should be a variable.
num_terms = 5
square_wave = square_wave_fourier(x, num_terms)
plt.figure(figsize=(8, 4))
plt.plot(x, square_wave, label=f'Square Wave (Terms = {num_terms})', color='blue')
plt.xlabel('Time')
plt.ylabel('Amplitude')
plt.title('Square Wave Approximation Using Fourier Series')
plt.grid(True)
plt.axhline(y=0, color='black', linewidth=0.5)
plt.axvline(x=0, color='black', linewidth=0.5)
plt.legend()
plt.show()
Write a Python program to read the x and y coordinates from a file, in a two-column format,
and plot them.
answer:First, ensure you have a file containing the x and y coordinates in a two-column
format. For example, you can have a file named coordinates.txt with the following content:
1.0 2.0 2.0 3.5 3.0 1.5 4.0 4.0 5.0 2.0
file_path = r'C:\Users\aswin\Downloads\Book1.txt'
try:
data = np.loadtxt(file_path)
x = data[:, 0]
y = data[:, 1]
except FileNotFoundError:
print(f"File '{file_path}' not found.")
except Exception as e:
print(f"An error occurred: {str(e)}")
In [ ]: import numpy as np
from mayavi import mlab
x = np.linspace(-5, 5, 100)
y = np.linspace(-5, 5, 100)
X, Y = np.meshgrid(x, y)
Z1, Z2 = surface_equation(X, Y)
mlab.xlabel("X")
mlab.ylabel("Y")
mlab.zlabel("Z")
C:\Users\aswin\AppData\Local\Temp\ipykernel_12260\1586635582.py:6: RuntimeWarning:
invalid value encountered in sqrt
return np.sqrt(25 - x**2 - y**2), -np.sqrt(25 - x**2 - y**2)
Make a plot z = sin(x) + sin(y) using imshow(), from −4π to 4π for both x and y.
X, Y = np.meshgrid(x, y)
Z = np.sin(X) + np.sin(Y)
y = x**2
plt.plot(x, y)
plt.xlabel('x')
plt.ylabel('y')
plt.show()
x = 0.5
terms = 10
y = 0
In [ ]: