Practical File
Course Title – Introduction to Computational
Physics
Course Code- PHY1003
Slot- A21+D11+D12
Winter Semester 2024-2025
Course Instructor - Dr. Geetanjali Giri
Name – Rudra Porwal
Reg No. 24BAI10485
Experiment 1: Visualizing Data with Python - Line Plots and Histograms
Aim:
To write a Python program using the `matplotlib` library to generate and display:
1. A line plot to visualize the trend of a given dataset.
2. A histogram to visualize the distribution of a given dataset.
Requirements:
Python 3, matplotlib, sample datasets for line plot and histogram, text editor/IDE.
Procedure:
import [Link] as plt
# Sample data for the line plot
days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
temperatures = [25, 26, 28, 27, 29, 30, 28]
# Sample data for the histogram
scores = [35, 42, 48, 29, 38, 45, 31, 40, 36, 49, 25, 33, 41, 47, 39, 30, 44, 37, 46,
32]
# Create the Line Plot
[Link](figsize=(8, 6))
[Link](days, temperatures, marker='o', linestyle='-', color='blue')
[Link]("Day of the Week")
[Link]("Temperature (°C)")
[Link]("Daily Temperature Trend")
[Link](True)
[Link]()
# Create the Histogram
[Link](figsize=(8, 6))
[Link](scores, bins=5, edgecolor='black', color='skyblue')
[Link]("Student Scores")
[Link]("Frequency")
[Link]("Distribution of Student Scores")
[Link](axis='y', alpha=0.75)
[Link]()
# Combine both plots (optional)
[Link](figsize=(12, 5))
[Link](1, 2, 1)
[Link](days, temperatures, marker='o', linestyle='-', color='blue')
[Link]("Day of the Week")
[Link]("Temperature (°C)")
[Link]("Daily Temperature Trend")
[Link](True)
[Link](1, 2, 2)
[Link](scores, bins=5, edgecolor='black', color='skyblue')
[Link]("Student Scores")
[Link]("Frequency")
[Link]("Distribution of Student Scores")
[Link](axis='y', alpha=0.75)
plt.tight_layout()
[Link]()
Output:
Observation: Line plot reveals data trends; histogram shows data frequency
distribution.
Precaution: Ensure matplotlib is installed, use relevant data, choose appropriate
histogram bins, label plots clearly, adjust plot parameters as needed.
Utilization: Data analysis, scientific research, education, business intelligence,
machine learning, data exploration.
Experiment 2: Matrix Multiplication in Python
Aim: To write a Python program to multiply two matrices.
Requirements: Python 3, understanding of matrix multiplication, sample matrices
(lists of lists).
Procedure:
def multiply_matrices(matrix1, matrix2):
rows1 = len(matrix1)
cols1 = len(matrix1[0])
rows2 = len(matrix2)
cols2 = len(matrix2[0])
if cols1 != rows2:
print("Error: Incompatible dimensions.")
return None
result = [[0 for _ in range(cols2)] for _ in range(rows1)]
for i in range(rows1):
for j in range(cols2):
for k in range(cols1):
result[i][j] += matrix1[i][k] * matrix2[k][j]
return result
matrix_a = [[1, 2, 3], [4, 5, 6]]
matrix_b = [[7, 8], [9, 10], [11, 12]]
product_matrix = multiply_matrices(matrix_a, matrix_b)
print("Matrix A:", matrix_a)
print("Matrix B:", matrix_b)
print("Product:", product_matrix)
Output:
Observation: Demonstrates matrix multiplication.
Precaution: Ensure compatible matrix dimensions for multiplication.
Utilization: Linear algebra, computer graphics, machine learning, image
processing, data analysis.
Experiment 3: Demonstration of the Central Limit Theorem in Python
Aim: To demonstrate the Central Limit Theorem (CLT) by observing the
distribution of sample means from a non-normal population.
Requirements: Python 3, numpy, matplotlib.
Procedure:
import numpy as np
import [Link] as plt
population_distribution = 'uniform'
population_parameters = {'low': 0, 'high': 1}
population_mean = [Link]([population_parameters['low'],
population_parameters['high']])
population_std = [Link]([Link](population_parameters['low'],
population_parameters['high'], 100000))
num_samples = 1000
sample_size = [5, 30, 100]
fig, axes = [Link](len(sample_size), 1, figsize=(10, 5 * len(sample_size)))
[Link](f'Demonstration of Central Limit Theorem (Population:
{population_distribution.capitalize()})', fontsize=16)
for i, n in enumerate(sample_size):
sample_means = []
for _ in range(num_samples):
if population_distribution == 'uniform':
sample = [Link](population_parameters['low'],
population_parameters['high'], n)
elif population_distribution == 'exponential':
sample = [Link](1/population_mean, n)
elif population_distribution == 'poisson':
sample = [Link](population_mean, n)
else:
raise ValueError("Unsupported population distribution")
sample_means.append([Link](sample))
axes[i].hist(sample_means, bins=30, density=True, alpha=0.6, color='skyblue')
mean_of_means = [Link](sample_means)
std_of_means = population_std / [Link](n)
x = [Link](min(sample_means), max(sample_means), 100)
axes[i].plot(x, 1/(std_of_means * [Link](2 * [Link])) * [Link]( - (x -
mean_of_means)**2 / (2 * std_of_means**2) ),
'r', linewidth=2, label=f'N({mean_of_means:.2f},
{std_of_means:.2f}^2)')
axes[i].set_xlabel('Sample Mean')
axes[i].set_ylabel('Density')
axes[i].set_title(f'Sample Size = {n}')
axes[i].legend()
axes[i].grid(True, linestyle='--', alpha=0.6)
plt.tight_layout(rect=[0, 0.03, 1, 0.95])
[Link]()
Output:
Observation: The distribution of sample means becomes increasingly normal as
the sample size grows, demonstrating the CLT.
Precaution: Ensure numpy and matplotlib are installed. Experiment with different
population distributions and sample sizes.
Utilization: Inferential statistics, data science, quality control, simulation, finance.
Experiment 4: Simulating Free Fall with Air Resistance in Python
Aim: To simulate and visualize free fall with air resistance.
Requirements: Python 3, numpy, matplotlib.
Procedure:
import numpy as np
import [Link] as plt
initial_height = 100
initial_velocity = 0
gravity = 9.81
air_resistance_coefficient = 0.01
mass = 0.1
time_step = 0.01
total_time = 10
time = [0]
height = [initial_height]
velocity = [initial_velocity]
current_time = 0
current_height = initial_height
current_velocity = initial_velocity
while current_height > 0 and current_time < total_time:
air_resistance_force = -air_resistance_coefficient * current_velocity *
abs(current_velocity)
net_force = mass * gravity + air_resistance_force
acceleration = net_force / mass
current_velocity = current_velocity + acceleration * time_step
current_height = current_height + current_velocity * time_step
current_time += time_step
[Link](current_time)
[Link](current_height)
[Link](current_velocity)
[Link](figsize=(10, 6))
[Link](2, 1, 1)
[Link](time, height)
[Link]("Time (s)")
[Link]("Height (m)")
[Link]("Height vs. Time (Free Fall with Air Resistance)")
[Link](True)
[Link](2, 1, 2)
[Link](time, velocity)
[Link]("Time (s)")
[Link]("Velocity (m/s)")
[Link]("Velocity vs. Time (Free Fall with Air Resistance)")
[Link](True)
plt.tight_layout()
[Link]()
Output:
Observation: Demonstrates terminal velocity and non-parabolic motion due to air
resistance.
Precaution: Ensure libraries are installed, adjust parameters to observe different
scenarios.
Utilization: Physics education, modeling real-world motion, understanding air
resistance effects.
Experiment 5: Simulating Projectile Motion in Python
Aim: To simulate and visualize the trajectory of projectile motion.
Requirements: Python 3, numpy, matplotlib.
Procedure:
import numpy as np
import [Link] as plt
initial_velocity = 30
launch_angle_degrees = 45
gravity = 9.81
time_step = 0.01
launch_angle_radians = np.deg2rad(launch_angle_degrees)
x = [0]
y = [0]
vx = initial_velocity * [Link](launch_angle_radians)
vy = initial_velocity * [Link](launch_angle_radians)
time = [0]
current_time = 0
while y[-1] >= 0:
current_time += time_step
[Link](current_time)
vy = vy - gravity * time_step
[Link](x[-1] + vx * time_step)
[Link](y[-1] + vy * time_step)
[Link](figsize=(8, 6))
[Link](x, y)
[Link]("Horizontal Distance (m)")
[Link]("Vertical Height (m)")
[Link]("Projectile Trajectory")
[Link](True)
[Link](0, color='black', linewidth=0.5)
[Link](0, color='black', linewidth=0.5)
[Link]()
print(f"Maximum Horizontal Range: {max(x):.2f} m")
print(f"Maximum Height: {max(y):.2f} m")
Output:
Observation: Visualizes the parabolic path of the projectile.
Precaution: Ensure libraries are installed, experiment with initial conditions.
Utilization: Physics education, visualizing motion, understanding trajectory
parameters.