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

CP-Post Mid

The document provides a series of programming exercises and concepts related to computational physics, including calculating sleep debt, factorials, Fibonacci series, and using the range function. It also covers modeling and simulation techniques in physics, random walk problems, and the importance of functions in Python programming. Various examples and activities are included to illustrate these concepts.

Uploaded by

km1703178
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)
9 views11 pages

CP-Post Mid

The document provides a series of programming exercises and concepts related to computational physics, including calculating sleep debt, factorials, Fibonacci series, and using the range function. It also covers modeling and simulation techniques in physics, random walk problems, and the importance of functions in Python programming. Various examples and activities are included to illustrate these concepts.

Uploaded by

km1703178
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

Computational Physics

P O S T - M I D

Sleep Debt
A “sleep debt” represents the difference between a person’s desirable and actual amount of sleep.
Write a program that prompts the user to enter how many hours they slept each day over a period
of seven days. Using 8 hours per day as the desirable amount of sleep, determine their sleep debt
by calculating the total hours of sleep they got over the seven-day period and subtracting that
from the total hours of sleep they should have got. If the user does not have a sleep debt, display
a message expressing your jealousy.

# initialize variables
total_sleep = 0
desirable_sleep = 8 * 7 # 8 hours per day over 7 days
sleep_debt = 0
# prompt user to enter hours of sleep for seven days
for i in range(7):
hours = int(input("Enter hours of sleep for day {}: ".format(i+1)))
total_sleep += hours
# calculate sleep debt
sleep_debt = desirable_sleep - total_sleep
# display results
if sleep_debt <= 0:
print("You do not have a sleep debt. I'm jealous!")
else:
print("Your sleep debt is {} hours.".format(sleep_debt))

Factorial
In mathematics, the notation n! represents the factorial of the nonnegative integer n. The factorial
of n is the product of all the nonnegative integers from 1 to n. For example,
7! = 1 x 2 x 3 x 4 x 5 x 6 x 7 = 5,040
Write a program that lets the user enter a nonnegative integer then uses a loop to calculate the
factorial of that number. Display the factorial.

n=int(input("Enter number:"))
fact=1
while(n>0):
fact=fact*n
n=n-1
print("Factorial of the number is: ", fact)

Fibonacci Series
Write a Python program to display Fibonacci numbers up to 20.

# initialize variables
a, b = 0, 1
# loop while a is less than or equal to 20
while a <= 20:
# print the current Fibonacci number followed by a tab
print(a, end='\t')
# update the values of a and b
a, b = b, a + b

Range Function
The program below uses the range function with a for loop to display “I love Pakistan” five
times.

# This program demonstrates how the range function can be used with a
for loop.
# Print a message five times.
for x in range(5):
print('I love Pakistan')

Arguments To The Range Function


The range function can get up to 3 arguments;
1. If 1 argument is passed to the range function, that argument is used as the ending limit of
the sequence of numbers.
2. If 2 arguments are passed to the range() function;
➢ the 1st argument is used as the starting value of the sequence
➢ the 2nd argument is used as the ending value
3. If 3 arguments are passed to the range function;
The 3rd argument is used as the step value. Instead of increasing by 1, each successive
number in the sequence will increase by the step value.

Examples
Write a program to print the first 10 natural numbers.

for n in range(1,11):
print(n)

Write a Python program that displays odd numbers between 1 and 10.

for num in range(1, 10, 2):


print(num)

Write a Python program that displays even numbers between 1 and 10.

for num in range(0, 10, 2):


print(num)

List Data Type


List is another data type with a collection of values. The following program demonstrates
working with List data type.

fruits = ['Mango', 'Apple', 'Orange', 'Cherry']


print(fruits)
print(type(fruits))
print(fruits[0]) #number enclosed in square brackets is called index
print(fruits[3])
#print(fruits[4]) #IndexError: list index out of range
print(len(fruits))
fruits.append('Banana')
print(fruits)
print(len(fruits))
print(fruits[-1])
print(fruits[-2])
print(fruits[-5])
#print(fruits[-6]) #IndexError: list index out of range
fruits[0] = 'Avocado'
print(fruits)
ACTIVITY
Here's a simple program that uses a list to store the velocities of five cars and calculates their
average velocity:

velocities = [10, 20, 15, 25, 30]

total_velocity = 0
for velocity in velocities:
total_velocity += velocity

average_velocity = total_velocity / len(velocities)

print("The average velocity of the five cars is:", average_velocity)

Modeling and Simulation


Modeling and simulation are two important techniques used in computational physics to
understand and analyze physical systems. In simple terms, modeling is the process of creating
a mathematical representation or a theoretical construct of a physical system, while simulation
involves using that model to make predictions about the behavior of the system.

Modeling
In computational physics, modeling involves creating mathematical equations that represent
physical systems, such as the motion of a particle or the behavior of a fluid. These equations
can be derived from first principles, such as the laws of motion or thermodynamics, or they can
be empirical, based on experimental data. Once a model has been created, it can be used to
simulate the behavior of the system over time.

Simulation
Simulation involves using the model to make predictions about the behavior of the system. This
can involve solving the equations that describe the system using numerical methods, such as
the finite difference or finite element method. These simulations can provide valuable insights
into the behavior of complex physical systems that may be difficult or impossible to study
experimentally.

One example of modeling and simulation in computational physics is the study of fluid
dynamics. Researchers can create mathematical models that describe the behavior of fluids,
such as the Navier-Stokes equations, and use simulations to study how fluids behave under
different conditions, such as in a pipe or around a moving object.
Importance
Modeling and simulation are two important techniques used in computational physics to
understand physical systems. Modeling involves creating mathematical representations of
physical systems, while simulation involves using those models to make predictions about the
behavior of the system. These techniques are essential for studying complex physical systems
that may be difficult or impossible to study experimentally.

Examples
1. Simulation of Bouncing of Ball Problem
# Bouncing ball physics problem
# Simulate the height of a bouncing ball over time

# Define variables
initial_height = 10 # height in meters
bounce_coefficient = 0.7 # energy retained after each bounce
num_bounces = 5 # number of bounces to simulate
# Calculate the height using a for loop
height = initial_height
for i in range(1,num_bounces+1):
height = height * bounce_coefficient**2
print(f"Bounce {i:d}, height {height:.2f} meters!")
print("The ball stopped bouncing after ", num_bounces," bounces.")

2. Simulation the motion of a Projectile


import math

#Define the constants


g = 9.81 # acceleration due to gravity in m/s^2
dt = 0.01 # time step in s

#Get the user input for the initial velocity and angle of launch
v_0 = float(input("Enter the initial velocity of the projectile in m/s: ")) # convert to
float
theta_0 = float(input("Enter the angle of launch of the projectile in degrees: ")) #
convert to float
theta_0 = math.radians(theta_0) # convert to radians

#Calculate the initial horizontal and vertical components of velocity


v_x = v_0 * math.cos(theta_0) # horizontal component in m/s
v_y = v_0 * math.sin(theta_0) # vertical component in m/s

#Initialize the position and time variables


x = 0 # horizontal position in m
y = 0 # vertical position in m
t = 0 # time in s

#Simulate the motion of the projectile using a loop


print('The motion of the projectile is simulated until it hits the ground.')
print(f'At time {t:.2f} s, the position of the projectile is ({x:.2f}, {y:.2f}) m.')
while y >= 0: # loop until y becomes negative (the projectile hits the ground)
x += v_x * dt # update x by adding the horizontal displacement
y += v_y * dt # update y by adding the vertical displacement
v_y -= g * dt # update v_y by subtracting the gravitational acceleration
t += dt # increment t by dt
print(f'At time {t:.2f} s, the position of the projectile is ({x:.2f}, {y:.2f}) m.')

#Print the final results


print('The projectile has landed.')
print(f'The total time of flight was {t:.2f} s.')
print(f'The maximum horizontal range was {x:.2f} m.')

Random Number
Here's a simple Python program that generates and displays a random number between 1 and 10
(inclusive) using the built-in random module:

import random # Import the random module

# Generate a random integer between 1 and 10 (inclusive)


random_number = random.randint(1, 10)

# Display the random number


print("Random number between 1 and 10:", random_number)

The random module is a built-in Python module that provides functions for generating random
numbers and sequences. It can be used to perform a variety of tasks, such as simulating random
events in games or generating random data for testing.
Random Walk Problem in Physics
In physics, the random walk problem refers to a mathematical model that describes the random
motion of a particle or system. The concept of a random walk is often used to analyze various
physical phenomena, such as diffusion, Brownian motion, and particle transport.

In a random walk, the motion of a particle or system is characterized by a series of discrete steps
taken in random directions. At each step, the particle moves a certain distance in a random
direction. The direction and distance of each step are determined independently and randomly.

The random walk problem can be approached in various ways depending on the specific context.
For example, in a one-dimensional random walk, the particle can only move along a line, while
in a two-dimensional random walk, the particle can move in any direction within a plane. The
random walk model can also be extended to three or more dimensions.

Applications

The random walk problem has applications in various areas of physics, such as statistical
physics, condensed matter physics, and biophysics. It is used to study the spreading of particles,
the behavior of polymers, the motion of molecules in a gas, and many other phenomena where
random motion plays a significant role.

ACTIVITY

Suppose a man is standing at point(5,5) in the x,y coordinate plane. The man is allowed 15 steps
and in 4 directions namely; front, back, right, and left. Each step covers a distance of 1 foot.
Write a fully commented Python program that simulates this. In the end, the program should find
and display displacement of the man from the starting point and his ending point in the x,y
coordinate plane.

import random
import math

# Function to simulate the random walk


def random_walk(steps):
# Starting position
x = 5 # x-coordinate
y = 5 # y-coordinate

# Step distance in foots


step_distance = 1
# Available directions: front, back, right, left
directions = ["front", "back", "right", "left"]

# Simulate the random walk


for _ in range(steps):
direction = random.choice(directions) # randomly choose a direction

# Update the position based on the chosen direction


if direction == "front":
y += step_distance
elif direction == "back":
y -= step_distance
elif direction == "right":
x += step_distance
elif direction == "left":
x -= step_distance

return x, y

# Simulate the random walk with 15 steps


num_steps = 15
final_x, final_y = random_walk(num_steps)

# Calculate the displacement from the starting point


displacement = math.sqrt((final_x - 5)**2 + (final_y - 5)**2)
displacement = round(displacement, 2)
# Print the results
print(f"Starting point: (5, 5)")
print(f"Ending point: ({final_x}, {final_y})")
print(f"Displacement: {displacement} foots")

Another Example
import random
print(random.uniform(2.5,4))
Functions in Python
A function is a group of statements that exist within a program for the purpose of performing a
specific task.
Instead of writing a large program as one long sequence of statements, it can be written as
several small functions, each one performing a specific part of the task. These small functions
can then be executed in the desired order to perform the overall task.
A program that has been written with each task in its own function is called a modularized
program and the approach is called “Divide and Conquer”.

This program is one long, complex In this program the task has been divided
sequence of statements. into smaller tasks, each of which is
performed by a separate function.

↓ ↓
Statement def fun1():
Statement Statement
Statement Statement
Statement …
Statement Statement
Statement
Statement
Statement def fun2():
Statement Statement
Statement Statement
Statement …
Statement Statement
Statement
Statement
Statement def fun3():
Statement Statement
Statement Statement
Statement …
Statement Statement
Statement

Example
Write a function that displays “I love Pakistan”. Use this function to exhibit its function.

def show(): #function's definition


print('I love Pakistan') #function's body

show() #function's call

Now, you can call the show() function as many times as you want and anywhere in the program.

ACTIVITY
Write a function to find the value of force in newton when it receives the values of mass in kg
and acceleration in m/s2.
Write the following user-defined functions. The names of the functions, the values that they
receive and return are given in the table below.

Function Name Details

1) The function should receive


a) Velocity in m/s
b) Angle in degrees
get_vx(v, ad)
2) The function should return
a) Horizontal component of
velocity in m/s

1) The function should receive


a) Velocity in m/s
b) Angle in degrees
get_vy(v, ad)
2) The function should return
a) Vertical component of velocity
in m/s

1. The function should receive


a. Horizontal component velocity
in m/s
dist_x(vx,t) b. Time in seconds
2. The function should return
a. Distance covered in m along
x-axis

1) The function should receive


a) Vertical component velocity in
m/s
dist_y(vy,t) b) Time in seconds
2) The function should return
a) Distance covered in m along
y-axis

You might also like