#the_numpy_array_
#size_shape_ndim_dtype
import numpy as np
#1_dtype
# Creating an array of integers with data type 'int16'
arrint16 = np.array([10, 20, 30], dtype=np.int16)
print(arrint16.dtype)
# Output: int16
# Creating an array of floats with data type 'float64'
arrfloat = np.array([1.1, 2.2, 3.3], dtype=np.float64)
print(arrfloat.dtype)
# Output: float64
import numpy as np
#2_size
#Creating a 2D array and calculating its size
arr1 = np.array([[1, 2, 3], [4, 5, 6]])
print(arr1.size)
# Output: 6
#Creating a 1D array and calculating its size
arr2 = np.array([10, 20, 30, 40, 50])
print(arr2.size)
# Output: 5
import numpy as np
#3_shape
#Creating a 3D array and checking its shape
arr3 = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]])
print(arr3.shape)
# Output: (3, 2, 2)
#Creating a 1D array and checking its shape
arr4 = np.array([1, 2, 3, 4, 5])
print(arr4.shape)
# 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
#Creating a 1D array and checking its number of dimensions
arr6 = np.array([10, 20, 30])
print(arr6.ndim)
# Output: 1
import numpy as np
#create_an_array_filled_with_zeros
arrzeros = np.zeros((2, 3))
print(arrzeros)
# Output:
# [[0. 0. 0.]
# [0. 0. 0.]]
import numpy as np
#array_filled_with_ones
arrones = np.ones((3, 2))
print(arrones)
# Output:
# [[1. 1.]
# [1. 1.]
# [1. 1.]]
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
arr = np.array([[1, 2, 3],
[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]]
#Important array methods
# Reshape
print("Reshape:")
print(arr.reshape(1, 9))
# Ravel
print("\nRavel:")
print(arr.ravel())
# Flatten
print("\nFlatten:")
print(arr.flatten())
# Hstack and Vstack
arr1 = np.array([[10, 11, 12]])
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:")
arr = np.array([[1, 2, 3],
[4, 5, 6]])
# Square each element
print(np.square(arr))
# Square root of each element
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. 1.41421356 1.73205081]
[2. 2.23606798 2.44948974]]
[[ 1 4 9]
[16 25 36]]
#np.sum_
import numpy as np
arr = np.array([[1, 2], [3, 4]])
sumresult = np.sum(arr)
print(sumresult)
#output: 10
#np.prod(): Computes the product of array elements over a specified axis.
import numpy as np
arr = np.array([[1, 2], [3, 4]])
prodresult = np.prod(arr)
print(prodresult)
#output: 24
#np.mean(): Computes the arithmetic mean along the specified axis.
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
meanresult = np.mean(arr)
print(meanresult)
#output: 3.0
#np.std(): Computes the standard deviation along the specified axis
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
stdresult = np.std(arr)
print(stdresult)
#output: 1.4142135623730951
#np.var(): Computes the variance along the specified axis.
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
varresult = np.var(arr)
print(varresult)
#output: 2.0
#np.min(): Returns the minimum value along the specified axis.
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
minresult = np.min(arr)
print(minresult)
#output: 1
#np.max(): Returns the maximum value along the specified axis.
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
maxresult = np.max(arr)
print(maxresult)
#output:5
#np.argmin(): Returns the indices of the minimum values along the specified axis.
arr= np.array([1, 2, 3, 4, 5])
argminresult = np.argmin(arr)
print(argminresult)
#output: 0
#np.argmax(): Returns the indices of the maximum values along the specified axis.
arr = np.array([1, 2, 3, 4, 5])
argmaxresult = np.argmax(arr)
print(argmaxresult)
#output: 4
#addition_and_multiplication_dot_products
import numpy as np
# Create two matrices
A = np.array([[1, 2], [3, 4]])
B = np.array([[5, 6], [7, 8]])
# Addition
C=A+B
print("Addition:")
print(C)
# Multiplication (Dot Product)
D = np.dot(A, B)
print("\nMultiplication (Dot Product):")
print(D)
#output:
#Addition:
[[ 6 8]
[10 12]]
#Multiplication (Dot Product):
[[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]])
# Using NumPy's linalg module to calculate the determinant
det_A = np.linalg.det(A)
print("Determinant of A:")
print(det_A)
#output:
#Determinant of A: 0.0
#solving linear equations_
import numpy as np
# Coefficients matrix
A = np.array([[2, 1], [1, -1]])
# Constants matrix
B = np.array([4, 1])
# Solve linear equations
solution = np.linalg.solve(A, B)
print("Solution:")
print(solution)
#output:
#Solution: [3. 1.]
#using NumPy linalg module for solving equation_
import numpy as np
# Coefficients matrix
A = np.array([[2, 1], [1, -1]])
# Constants matrix
B = np.array([4, 1])
# Solve linear equations using linalg.solve
solution = np.linalg.solve(A, B)
print("Solution:")
print(solution)
#output:
# Solution:[3. 1.]
#Diagonalization
import numpy as np
# Create a matrix
A = np.array([[1, 2], [3, 4]])
# Diagonalize the matrix
eigenvalues, eigenvectors = np.linalg.eig(A)
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
import matplotlib.pyplot as plt
from scipy.interpolate import lagrange, interp1d
# Sample data points
x = np.array([1, 2, 3, 4])
y = np.array([4, 2, 1, 3])
# Lagrange Interpolation
lag_poly = lagrange(x, y)
# Newton Forward Interpolation
newton_poly = interp1d(x, y, kind='linear')
# Generate more points for smooth curve
x_interp = np.linspace(min(x), max(x), 100)
y_interp_lag = lag_poly(x_interp)
y_interp_newton = newton_poly(x_interp)
# Plotting
plt.figure(figsize=(10, 6))
plt.plot(x, y, 'o', label='Data Points')
plt.plot(x_interp, y_interp_lag, label='Lagrange Interpolation')
plt.plot(x_interp, y_interp_newton, label='Newton Forward Interpolation')
plt.title('Interpolation Methods Comparison')
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.grid(True)
plt.show()
Output:
#2
import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import lagrange, interp1d
# Sample data points
x = np.array([1, 2, 3, 4, 5])
y = np.array([5, 3, 2, 4, 6])
# Lagrange Interpolation
lag_poly = lagrange(x, y)
# Newton Forward Interpolation
newton_poly = interp1d(x, y, kind='linear')
# Generate more points for smooth curve
x_interp = np.linspace(min(x), max(x), 100)
y_interp_lag = lag_poly(x_interp)
y_interp_newton = newton_poly(x_interp)
# Plotting
plt.figure(figsize=(10, 6))
plt.plot(x, y, 'o', label='Data Points')
plt.plot(x_interp, y_interp_lag, label='Lagrange Interpolation')
plt.plot(x_interp, y_interp_newton, label='Newton Forward Interpolation')
plt.title('Interpolation Methods Comparison')
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.grid(True)
plt.show()
#output:
#with oscillating data points_
import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import lagrange, interp1d
# Sample oscillating data points
x = np.linspace(0, 10, 20)
y = np.sin(x)
# Lagrange Interpolation
lag_poly = lagrange(x, y)
# Newton Forward Interpolation
newton_poly = interp1d(x, y, kind='linear')
# Generate more points for smooth curve
x_interp = np.linspace(min(x), max(x), 100)
y_interp_lag = lag_poly(x_interp)
y_interp_newton = newton_poly(x_interp)
# Plotting
plt.figure(figsize=(10, 6))
plt.plot(x, y, 'o', label='Data Points')
plt.plot(x_interp, y_interp_lag, label='Lagrange Interpolation')
plt.plot(x_interp, y_interp_newton, label='Newton Forward Interpolation')
plt.title('Interpolation Methods Comparison')
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
from scipy.integrate import quad, trapz, simps
# Define a sample function
def func(x):
return np.sin(x)
# Define the interval
a=0
b = np.pi
# Number of sample points
n = 100
# Trapezoidal Rule using numpy
x = np.linspace(a, b, n)
y = func(x)
trapezoidal_result_numpy = np.trapz(y, x)
# Trapezoidal Rule using scipy
trapezoidal_result_scipy = trapz(y, x)
# Simpson's One-Third Rule using numpy
simpsons_result_numpy = np.sum(simps(y, x))
# Simpson's One-Third Rule using scipy
simpsons_result_scipy = simps(y, x)
# Numerical integration using quad function from scipy
quad_result, _ = quad(func, a, b)
print("Trapezoidal Rule (numpy):", trapezoidal_result_numpy)
print("Trapezoidal Rule (scipy):", trapezoidal_result_scipy)
print("Simpson's One-Third Rule (numpy):", simpsons_result_numpy)
print("Simpson's One-Third Rule (scipy):", simpsons_result_scipy)
print("Quad (scipy.integrate.quad()):", quad_result)
#output:
#Trapezoidal Rule (numpy): 1.9998321638939929
#Trapezoidal Rule (scipy): 1.9998321638939929
#Simpson's One-Third Rule (numpy): 1.9999999690165369
#Simpson's One-Third Rule (scipy): 1.9999999690165369
#Quad (scipy.integrate.quad()): 2.0
#integrating the function [f(x) = x³-2x²+x+1] over the interval ([0, 2])
import numpy as np
# Define the function
def func(x):
return x**3 - 2*x**2 + x + 1
# Define the interval
a=0
b=2
# Number of sample points
n = 1000
# Trapezoidal Rule
x_trap = np.linspace(a, b, n)
y_trap = func(x_trap)
trapezoidal_result = np.trapz(y_trap, x_trap)
# Simpson's One-Third Rule
x_simpson = np.linspace(a, b, n+1)
y_simpson = func(x_simpson)
h = (b - a) / n
simpsons_result = h/3 * (y_simpson[0] + y_simpson[-1] + 4*np.sum(y_simpson[1:-1:2]) +
2*np.sum(y_simpson[2:-1:2]))
print("Trapezoidal Rule:", trapezoidal_result)
print("Simpson's One-Third Rule:", simpsons_result)
#output:
#Trapezoidal Rule: 4.666666666666667
#Simpson's One-Third Rule: 4.666666666666667
#solution of ODE
import numpy as np
# Define the RK4 algorithm for first-order ODE
def rk4_first_order(func, y0, x_range, h):
n = len(x_range)
y = np.zeros(n)
y[0] = y0
for i in range(1, n):
k1 = h * func(x_range[i-1], y[i-1])
k2 = h * func(x_range[i-1] + 0.5 * h, y[i-1] + 0.5 * k1)
k3 = h * func(x_range[i-1] + 0.5 * h, y[i-1] + 0.5 * k2)
k4 = h * func(x_range[i-1] + h, y[i-1] + k3)
y[i] = y[i-1] + (k1 + 2*k2 + 2*k3 + k4) / 6
return y
# Define the RK4 algorithm for second-order ODE
def rk4_second_order(func, y0, dy0, x_range, h):
n = len(x_range)
y = np.zeros(n)
dy = np.zeros(n)
y[0] = y0
dy[0] = dy0
for i in range(1, n):
k1 = h * dy[i-1]
l1 = h * func(x_range[i-1], y[i-1], dy[i-1])
k2 = h * (dy[i-1] + 0.5 * l1)
l2 = h * func(x_range[i-1] + 0.5 * h, y[i-1] + 0.5 * k1, dy[i-1] + 0.5 * l1)
k3 = h * (dy[i-1] + 0.5 * l2)
l3 = h * func(x_range[i-1] + 0.5 * h, y[i-1] + 0.5 * k2, dy[i-1] + 0.5 * l2)
k4 = h * (dy[i-1] + l3)
l4 = h * func(x_range[i-1] + h, y[i-1] + k3, dy[i-1] + l3)
y[i] = y[i-1] + (k1 + 2*k2 + 2*k3 + k4) / 6
dy[i] = dy[i-1] + (l1 + 2*l2 + 2*l3 + l4) / 6
return y, dy
# Example: Solve the first-order ODE dy/dx = -2y
def func_first_order(x, y):
return -2 * y
# Example: Solve the second-order ODE d^2y/dx^2 = -y with initial conditions y(0) = 0, dy(0)/dx = 1
def func_second_order(x, y, dy):
return -y
# Define the range and step size
x_range = np.linspace(0, 2, 101)
h = x_range[1] - x_range[0]
# Solve the first-order ODE using RK4
y0 = 1 # initial condition: y(0) = 1
y_solution_first_order = rk4_first_order(func_first_order, y0, x_range, h)
# Solve the second-order ODE using RK4
y0_second_order = 0 # initial condition: y(0) = 0
dy0_second_order = 1 # initial condition: dy/dx(0) = 1
y_solution_second_order, dy_solution_second_order = rk4_second_order(func_second_order, y0_second_order,
dy0_second_order, x_range, h)
print("First-order ODE Solution (RK4):", y_solution_first_order)
print("Second-order ODE Solution (RK4):", y_solution_second_order)
#output:
#First-order ODE Solution (RK4): [1. 0.96078944 0.92311635 0.88692044 0.85214379 0.81873076
0.78662787 0.75578375 0.72614904 0.69767633 0.67032005 0.64403643
0.6187834 0.59452055 0.57120907 0.54881164 0.52729243 0.506617
0.48675226 0.46766643 0.44932897 0.43171053 0.41478292 0.39851905
0.38289289 0.36787945 0.35345469 0.33959553 0.3262798 0.31348619
0.30119422 0.28938423 0.27803731 0.26713531 0.25666078 0.24659697
0.23692777 0.2276377 0.21871189 0.21013608 0.20189653 0.19398005
0.18637398 0.17906615 0.17204487 0.16529889 0.15881743 0.15259011
0.14660697 0.14085843 0.13533529 0.13002872 0.12493022 0.12003163
0.11532513 0.11080316 0.10645851 0.10228421 0.09827359 0.09442023
0.09071796 0.08716086 0.08374323 0.08045961 0.07730474 0.07427358
0.07136127 0.06856316 0.06587476 0.06329177 0.06081007 0.05842567
0.05613477 0.05393369 0.05181892 0.04978707 0.04783489 0.04595926
0.04415717 0.04242574 0.04076221 0.0391639 0.03762826 0.03615283
0.03473526 0.03337327 0.03206469 0.03080741 0.02959944 0.02843883
0.02732372 0.02625235 0.02522298 0.02423397 0.02328374 0.02237077
0.0214936 0.02065083 0.0198411 0.01906312 0.01831564]
#Second-order ODE Solution (RK4): [0. 0.01999867 0.03998933 0.05996401 0.07991469 0.09983342
0.11971221 0.13954311 0.15931821 0.17902957 0.19866933 0.21822962
0.23770263 0.25708055 0.27635565 0.29552021 0.31456656 0.33348709
0.35227423 0.37092047 0.38941834 0.40776045 0.42593946 0.44394811
0.46177917 0.47942554 0.49688014 0.51413599 0.5311862 0.54802394
0.56464247 0.58103516 0.59719544 0.61311685 0.62879302 0.64421769
0.65938467 0.67428791 0.68892144 0.70327942 0.71735609 0.73114583
0.74464312 0.75784256 0.77073888 0.78332691 0.79560162 0.8075581
0.81919157 0.83049737 0.84147098 0.85210802 0.86240423 0.87235548
0.88195781 0.89120736 0.90010044 0.9086335 0.91680311 0.92460601
0.93203909 0.93909936 0.945784 0.95209034 0.95801586 0.96355818
0.9687151 0.97348454 0.9778646 0.98185353 0.98544973 0.98865176
0.99145835 0.99386836 0.99588084 0.99749499 0.99871014 0.99952583
0.99994172 0.99995765 0.9995736 0.99878974 0.99760638 0.99602399
0.9940432 0.99166481 0.98888977 0.98571918 0.98215432 0.97819661
0.97384763 0.96910913 0.963983 0.95847128 0.95257619 0.94630009
0.93964547 0.93261501 0.92521152 0.91743796 0.90929743]
#CURVE FITTING
#examples of both the methods
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
# Sample data
x_data = np.array([1, 2, 3, 4, 5])
y_data = np.array([2.5, 3.5, 4.5, 5.5, 6.5])
# Curve fitting with numpy polynomials
degree = 2
coefficients = np.polyfit(x_data, y_data, degree)
poly_fit = np.poly1d(coefficients)
x_range = np.linspace(min(x_data), max(x_data), 100)
y_fit_poly = poly_fit(x_range)
# Curve fitting with user-defined function
def func(x, a, b):
return a * x + b
params, _ = curve_fit(func, x_data, y_data)
a_fit, b_fit = params
y_fit_custom = func(x_range, a_fit, b_fit)
# Plotting
plt.figure(figsize=(10, 6))
plt.scatter(x_data, y_data, label='Data Points')
plt.plot(x_range, y_fit_poly, label='Polynomial Fit (Numpy)')
plt.plot(x_range, y_fit_custom, label='Custom Function Fit (Scipy)')
plt.title('Curve Fitting Comparison')
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.grid(True)
plt.show()
#output:
#2
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
# Generate sample data
np.random.seed(0)
x_data = np.linspace(0, 10, 100)
y_data = 2 * np.sin(x_data) + np.random.normal(0, 0.5, 100)
# Define a user-defined function for curve fitting
def func(x, a, b, c):
return a * np.sin(b * x + c)
# Perform curve fitting
params, _ = curve_fit(func, x_data, y_data, p0=[2, 1, 0])
# Generate fitted curve
y_fit = func(x_data, *params)
# Plotting
plt.figure(figsize=(10, 6))
plt.scatter(x_data, y_data, label='Data Points')
plt.plot(x_data, y_fit, color='red', label='Fitted Curve')
plt.title('Curve Fitting Example')
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.grid(True)
plt.show()
#output:
#matplotlib's pyplot submodule_
#figure, axes, subplot
import matplotlib.pyplot as plt
# Creating a figure and a set of subplots
fig, ax = plt.subplots(nrows=2, ncols=2)
#plot(), scatter (), show()
import numpy as np
x = np.linspace(0, 10, 100)
y = np.sin(x)
plt.plot(x, y)
# or plt.scatter(x, y) for scatter plot
plt.show()
#output:
#labels, legends, titles, ticks, styles_
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 2*np.pi, 100) # Define x from 0 to 2*pi
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
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
# Generate some data
x = np.linspace(0, 10, 100)
y = np.sin(x)
# Create a figure and axis
fig, ax = plt.subplots()
line, = ax.plot(x, y)
# Function to update the plot
def update_plot(frame):
# Update the data
line.set_ydata(np.sin(x + frame * 0.1))
return line,
# Animate the plot
ani = FuncAnimation(fig, update_plot, frames=range(100), blit=True)
plt.show()
#output:
#saving graphs
plt.savefig('sine_plot.png')