0% found this document useful (0 votes)
3 views11 pages

Practical File Physics

The document outlines a practical file for the course 'Introduction to Computational Physics' with experiments focusing on data visualization, matrix multiplication, the Central Limit Theorem, free fall simulation, and projectile motion simulation using Python. Each experiment includes aims, requirements, procedures, observations, precautions, and potential utilizations in various fields. The instructor is Dr. Geetanjali Giri, and the student is Rudra Porwal.

Uploaded by

rudraporwal8
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views11 pages

Practical File Physics

The document outlines a practical file for the course 'Introduction to Computational Physics' with experiments focusing on data visualization, matrix multiplication, the Central Limit Theorem, free fall simulation, and projectile motion simulation using Python. Each experiment includes aims, requirements, procedures, observations, precautions, and potential utilizations in various fields. The instructor is Dr. Geetanjali Giri, and the student is Rudra Porwal.

Uploaded by

rudraporwal8
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

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 matplotlib.pyplot 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


plt.figure(figsize=(8, 6))
plt.plot(days, temperatures, marker='o', linestyle='-', color='blue')
plt.xlabel("Day of the Week")
plt.ylabel("Temperature (°C)")
plt.title("Daily Temperature Trend")
plt.grid(True)
plt.show()

# Create the Histogram


plt.figure(figsize=(8, 6))
plt.hist(scores, bins=5, edgecolor='black', color='skyblue')
plt.xlabel("Student Scores")
plt.ylabel("Frequency")
plt.title("Distribution of Student Scores")
plt.grid(axis='y', alpha=0.75)
plt.show()

# Combine both plots (optional)


plt.figure(figsize=(12, 5))
plt.subplot(1, 2, 1)
plt.plot(days, temperatures, marker='o', linestyle='-', color='blue')
plt.xlabel("Day of the Week")
plt.ylabel("Temperature (°C)")
plt.title("Daily Temperature Trend")
plt.grid(True)
plt.subplot(1, 2, 2)
plt.hist(scores, bins=5, edgecolor='black', color='skyblue')
plt.xlabel("Student Scores")
plt.ylabel("Frequency")
plt.title("Distribution of Student Scores")
plt.grid(axis='y', alpha=0.75)
plt.tight_layout()
plt.show()

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 matplotlib.pyplot as plt

population_distribution = 'uniform'
population_parameters = {'low': 0, 'high': 1}
population_mean = np.mean([population_parameters['low'],
population_parameters['high']])
population_std = np.std(np.random.uniform(population_parameters['low'],
population_parameters['high'], 100000))
num_samples = 1000
sample_size = [5, 30, 100]
fig, axes = plt.subplots(len(sample_size), 1, figsize=(10, 5 * len(sample_size)))
fig.suptitle(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 = np.random.uniform(population_parameters['low'],
population_parameters['high'], n)
elif population_distribution == 'exponential':
sample = np.random.exponential(1/population_mean, n)
elif population_distribution == 'poisson':
sample = np.random.poisson(population_mean, n)
else:
raise ValueError("Unsupported population distribution")
sample_means.append(np.mean(sample))
axes[i].hist(sample_means, bins=30, density=True, alpha=0.6, color='skyblue')
mean_of_means = np.mean(sample_means)
std_of_means = population_std / np.sqrt(n)
x = np.linspace(min(sample_means), max(sample_means), 100)
axes[i].plot(x, 1/(std_of_means * np.sqrt(2 * np.pi)) * np.exp( - (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])


plt.show()

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 matplotlib.pyplot 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
time.append(current_time)
height.append(current_height)
velocity.append(current_velocity)

plt.figure(figsize=(10, 6))
plt.subplot(2, 1, 1)
plt.plot(time, height)
plt.xlabel("Time (s)")
plt.ylabel("Height (m)")
plt.title("Height vs. Time (Free Fall with Air Resistance)")
plt.grid(True)
plt.subplot(2, 1, 2)
plt.plot(time, velocity)
plt.xlabel("Time (s)")
plt.ylabel("Velocity (m/s)")
plt.title("Velocity vs. Time (Free Fall with Air Resistance)")
plt.grid(True)
plt.tight_layout()
plt.show()

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 matplotlib.pyplot 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 * np.cos(launch_angle_radians)
vy = initial_velocity * np.sin(launch_angle_radians)
time = [0]
current_time = 0

while y[-1] >= 0:


current_time += time_step
time.append(current_time)
vy = vy - gravity * time_step
x.append(x[-1] + vx * time_step)
y.append(y[-1] + vy * time_step)

plt.figure(figsize=(8, 6))
plt.plot(x, y)
plt.xlabel("Horizontal Distance (m)")
plt.ylabel("Vertical Height (m)")
plt.title("Projectile Trajectory")
plt.grid(True)
plt.axhline(0, color='black', linewidth=0.5)
plt.axvline(0, color='black', linewidth=0.5)
plt.show()

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.

You might also like