Python 20240309 154846 0000
Python 20240309 154846 0000
#size_shape_ndim_dtype
import numpy as np
#1_dtype
print(arrint16.dtype)
# Output: int16
# Output: float64
import numpy as np
#2_size
# Output: 6
# Output: 5
import numpy as np
#3_shape
# Output: (3, 2, 2)
# Output: (5,)
import numpy as np
#4_ndim
#Creating a 2D array and checking its number of dimensions
arr5 = np.array([[1, 2, 3], [4, 5, 6]])
print(arr5.ndim)
# Output: 2
# Output: 1
import numpy as np
#create_an_array_filled_with_zeros
import numpy as np
#array_filled_with_ones
import numpy as np
#array_filled_with_specified_value
arrfull = np.full((2, 2), 5)
print(arrfull)
# Output:
# [[5 5]
# [5 5]]
import numpy as np
#array_with_range_of_values
arrarange = np.arange(1, 10, 2)
print(arrarange)
# Output: [1 3 5 7 9]
import numpy as np
#array with evenly spaced value
arrlinspace = np.linspace(0, 10, 5)
print(arrlinspace)
# Output: [ 0. 2.5 5. 7.5 10. ]
import numpy as np
#array with values spaced evenly on a logarithmic scale
arrlogspace = np.logspace(1, 3, 4)
print(arrlogspace)
# Output: [ 10. 46.4 215.4 1000. ]
import numpy as np
#square identity matrix
arridentity = np.identity(3)
print(arridentity)
# Output:
# [[1. 0. 0.]
# [0. 1. 0.]
# [0. 0. 1.]]
import numpy as np
#2D array with ones in the diagonal
arreye = np.eye(3, 4)
print(arreye)
# Output:
# [[1. 0. 0. 0.]
# [0. 1. 0. 0.]
# [0. 0. 1. 0.]]
import numpy as np
#array into specific data type
arr = np.array([1, 2, 3])
arrnew = arr.astype(float)
print(arrnew)
# Output: [1. 2. 3.]
import numpy as np
import numpy as np
# Creating a sample array
[4, 5,6],
[7, 8,9]])
# Indexing
print("Indexing:")
print(arr[0, 0])
print(arr[1])
print(arr[:, 1])
# Slicing
print("\nSlicing:")
print(arr[0:2, 1:])
#output:
#Indexing:
#[4 5 6]
#[2 5 8]
#Slicing:
#[[2 3]
# [5 6]]
# Reshape
print("Reshape:")
print(arr.reshape(1, 9))
# Ravel
print("\nRavel:")
print(arr.ravel())
# Flatten
print("\nFlatten:")
print(arr.flatten())
# Hstack and Vstack
print("\nHstack:")
print(np.hstack((arr, arr1)))
arr2 = np.array([[13],
[14],
[15]])
print("\nVstack:")
print(np.vstack((arr, arr2)))
#output:
#Reshape:
[[1 2 3 4 5 6 7 8 9]]
#Ravel:
[1 2 3 4 5 6 7 8 9]
#Flatten:
[1 2 3 4 5 6 7 8 9]
#Hstack:
[[ 1 2 3 10 11 12]]
#Vstack:
[[ 1 2 3]
[ 4 5 6]
[ 7 8 9]
[13 14 15]]
# Element-wise functions
print("\nElement-wise Functions:")
[4, 5, 6]])
print(np.square(arr))
print(np.sqrt(arr))
# Using vectorize
vec_square = np.vectorize(lambda x: x ** 2)
print(vec_square(arr))
#output:
#Element-wise Functions:
[[ 1 4 9]
[16 25 36]]
[[ 1 4 9]
[16 25 36]]
#np.sum_
import numpy as np
sumresult = np.sum(arr)
print(sumresult)
#output: 10
import numpy as np
prodresult = np.prod(arr)
print(prodresult)
#output: 24
import numpy as np
meanresult = np.mean(arr)
print(meanresult)
#output: 3.0
import numpy as np
stdresult = np.std(arr)
print(stdresult)
#output: 1.4142135623730951
varresult = np.var(arr)
print(varresult)
#output: 2.0
import numpy as np
minresult = np.min(arr)
print(minresult)
#output: 1
import numpy as np
maxresult = np.max(arr)
print(maxresult)
#output:5
#np.argmin(): Returns the indices of the minimum values along the specified axis.
argminresult = np.argmin(arr)
print(argminresult)
#output: 0
#np.argmax(): Returns the indices of the maximum values along the specified axis.
argmaxresult = np.argmax(arr)
print(argmaxresult)
#output: 4
#addition_and_multiplication_dot_products
import numpy as np
# Addition
C=A+B
print("Addition:")
print(C)
D = np.dot(A, B)
print(D)
#output:
#Addition:
[[ 6 8]
[10 12]]
[[19 22]
[43 50]]
#Gauss elimination (with partial pivoting)_
import numpy as np
# Create a matrix
A = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
det_A = np.linalg.det(A)
print("Determinant of A:")
print(det_A)
#output:
#Determinant of A: 0.0
import numpy as np
# Coefficients matrix
# Constants matrix
B = np.array([4, 1])
solution = np.linalg.solve(A, B)
print("Solution:")
print(solution)
#output:
import numpy as np
# Coefficients matrix
# Constants matrix
B = np.array([4, 1])
solution = np.linalg.solve(A, B)
print("Solution:")
print(solution)
#output:
# Solution:[3. 1.]
#Diagonalization
import numpy as np
# Create a matrix
print("Eigenvalues:")
print(eigenvalues)
print("\nEigenvectors:")
print(eigenvectors)
#output:
#Eigenvalues:
[-0.37228132 5.37228132]
#Eigenvectors:
[[-0.82456484 -0.41597356]
[0.56576746 -0.90937671]]
#INTERPOLATION USING NumPy and scipy.interpolate for visualization_
#1
import numpy as np
x = np.array([1, 2, 3, 4])
y = np.array([4, 2, 1, 3])
# Lagrange Interpolation
lag_poly = lagrange(x, y)
y_interp_lag = lag_poly(x_interp)
y_interp_newton = newton_poly(x_interp)
# Plotting
plt.figure(figsize=(10, 6))
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.grid(True)
plt.show()
Output:
#2
import numpy as np
x = np.array([1, 2, 3, 4, 5])
y = np.array([5, 3, 2, 4, 6])
# Lagrange Interpolation
lag_poly = lagrange(x, y)
y_interp_lag = lag_poly(x_interp)
y_interp_newton = newton_poly(x_interp)
# Plotting
plt.figure(figsize=(10, 6))
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.grid(True)
plt.show()
#output:
#with oscillating data points_
import numpy as np
y = np.sin(x)
# Lagrange Interpolation
lag_poly = lagrange(x, y)
y_interp_lag = lag_poly(x_interp)
y_interp_newton = newton_poly(x_interp)
# Plotting
plt.figure(figsize=(10, 6))
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.grid(True)
plt.show()
#output:
#trapezoidal rule and Simpsons 1/3rd rule using both numpy and scipy
import numpy as np
def func(x):
return np.sin(x)
a=0
b = np.pi
n = 100
x = np.linspace(a, b, n)
y = func(x)
trapezoidal_result_numpy = np.trapz(y, x)
trapezoidal_result_scipy = trapz(y, x)
# Simpson's One-Third Rule using numpy
simpsons_result_scipy = simps(y, x)
quad_result, _ = quad(func, a, b)
#output:
import numpy as np
def func(x):
a=0
b=2
n = 1000
# Trapezoidal Rule
x_trap = np.linspace(a, b, n)
y_trap = func(x_trap)
y_simpson = func(x_simpson)
h = (b - a) / n
#output:
import numpy as np
n = len(x_range)
y = np.zeros(n)
y[0] = y0
k1 = h * func(x_range[i-1], y[i-1])
return y
y = np.zeros(n)
dy = np.zeros(n)
y[0] = y0
dy[0] = dy0
k1 = h * dy[i-1]
k4 = h * (dy[i-1] + l3)
return y, dy
return -2 * y
# Example: Solve the second-order ODE d^2y/dx^2 = -y with initial conditions y(0) = 0, dy(0)/dx = 1
return -y
h = x_range[1] - x_range[0]
#output:
#First-order ODE Solution (RK4): [1. 0.96078944 0.92311635 0.88692044 0.85214379 0.81873076
#Second-order ODE Solution (RK4): [0. 0.01999867 0.03998933 0.05996401 0.07991469 0.09983342
import numpy as np
# Sample data
degree = 2
poly_fit = np.poly1d(coefficients)
y_fit_poly = poly_fit(x_range)
return a * x + b
plt.figure(figsize=(10, 6))
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.grid(True)
plt.show()
#output:
#2
import numpy as np
np.random.seed(0)
return a * np.sin(b * x + c)
# Plotting
plt.figure(figsize=(10, 6))
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.grid(True)
plt.show()
#output:
#matplotlib's pyplot submodule_
import numpy as np
y = np.sin(x)
plt.plot(x, y)
plt.show()
#output:
#labels, legends, titles, ticks, styles_
import numpy as np
y = np.sin(x)
plt.plot(x, y, label='sin(x)')
plt.xlabel('x')
plt.ylabel('y')
plt.title('Sine Function')
plt.legend()
plt.grid(True)
plt.show()
#output:
#dynamical updating curves
import numpy as np
y = np.sin(x)
fig, ax = plt.subplots()
line, = ax.plot(x, y)
def update_plot(frame):
return line,
plt.show()
#output:
#saving graphs
plt.savefig('sine_plot.png')