0% found this document useful (0 votes)
4 views7 pages

programme

The document contains a series of Python programming exercises related to random number generation, statistical analysis, file handling, and data visualization. Key tasks include generating random numbers, calculating means and standard deviations, simulating a dice battle, and reading/writing temperature and earthquake data from/to files. Additionally, it includes instructions for plotting a mathematical function using matplotlib.

Uploaded by

rogerbarman2026
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)
4 views7 pages

programme

The document contains a series of Python programming exercises related to random number generation, statistical analysis, file handling, and data visualization. Key tasks include generating random numbers, calculating means and standard deviations, simulating a dice battle, and reading/writing temperature and earthquake data from/to files. Additionally, it includes instructions for plotting a mathematical function using matplotlib.

Uploaded by

rogerbarman2026
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

In [2]: # Name: Arpan Purkait

# Roll: 002320701045
# Date: 15 Apr, 2025

# [Link] Physics
# IDC(3): Modern Computational Method

# Problem Set: 3

In [3]: # Random Numbers

In [4]: # Generate 100 integer random numbers that follow uniform distribution
# between (1,100). Then, find the mean.

In [5]: import random as rand

In [6]: i = 0; s = 0; kn = 100

while i < kn:


number = [Link](1,100)
print(number,end=' ')
s = s + number; i = i + 1

mean = s/kn
print("\n")
print(f"The Mean is {mean}")

68 39 38 91 67 64 39 12 78 94 68 15 33 55 7 60 74 94 13 9 21 36 97 73 17 57 62 95 54 67 3 47 98 79 82 20 33 63
1 99 50 44 11 39 32 17 74 82 54 49 79 65 40 19 76 43 49 25 17 95 88 81 52 62 11 99 50 31 30 96 78 63 79 76 38 3
2 98 93 75 20 51 34 29 65 98 12 87 16 33 80 94 12 4 33 13 43 39 69 15 60

The Mean is 52.21

In [7]: # Find 100 random number that follow Gaussian distribution


# (normal distribution) with mean “zero” and standard deviation “1”.
# Then calculate the mean and standard deviation of those numbers.

In [8]: import numpy as np

In [9]: kn = 100
mean = 0.0; std = 1

data = [Link](100)

for i in range(100):
data[i] = [Link](mean,std)

print(data)
print("\n")

print(f'The Mean is: {[Link](data)}')


print(f'The Standard Deviation is: {[Link](data)}')

[ 2.05961683 -0.31771214 -0.26816164 -0.6412172 0.26162649 -0.33960121


1.21645996 -1.37655386 0.54595382 2.02018177 0.19451717 3.31818293
0.1339507 -0.83259405 0.11197834 0.78164425 -0.74312559 0.91387599
-1.5815969 0.52950094 0.54888031 0.2013208 1.14054791 0.28270772
0.24957815 0.31577448 0.03587757 -0.47863288 -0.80143438 -0.07839213
-1.00295411 0.6894759 -0.98920202 -0.13949025 0.86745403 -0.41857333
-1.62963604 0.87670126 -0.15029037 -0.8797955 -0.95793652 0.20898216
1.83889527 1.48241725 -0.52109117 -0.02875204 -0.7134636 -0.72417989
-1.17332918 -2.51228048 -0.07294969 -1.34906693 0.75402013 1.39162996
-0.87155178 0.75908384 -0.07076196 -0.49566074 -1.879733 -0.81606343
2.22504421 -0.57467571 0.10646565 1.18084536 2.22778027 0.1365299
1.26435593 -1.19163031 0.95285527 -0.41629776 0.46146504 1.35806798
-0.4683653 -0.33435263 -0.23686205 0.4159899 0.54918371 0.37262008
-0.94047721 -0.77634482 1.68703271 0.21258908 -0.25894699 0.25084975
0.62208769 -0.49812842 -1.22236274 -0.89742811 -1.56048724 0.96321052
0.67890279 0.23830181 0.62218569 1.34191399 0.90003806 -0.16535022
-0.45112883 0.5016012 0.25843247 2.1769407 ]

The Mean is: 0.10587503350185905


The Standard Deviation is: 1.0132778794344335

In [10]: # Simulate a battle between two players rolling a 6-sided die.


# The player with the higher roll wins the round.
# Determine the winner after 10 rounds.

In [11]: def battle():


s1, s2 = 0.0, 0.0
print("---------------------------")
print("| Round| Player1 |Player2|")
for i in range(10):
num1 = [Link](1,6)
num2 = [Link](1,6)
print("|-------------------------|")
print(f"| {i+1:3} | {num1} | {num2} |")
s1 = s1 + num1
s2 = s2 + num2
print("|-------------------------|")
print(f"| Total | {s1} | {s2} |")
print("---------------------------")
print("Congratulations! Player 1 Wins.") if(s1>s2) else print("Congratulations! Player 2 Wins.")

battle()

---------------------------
| Round| Player1 |Player2|
|-------------------------|
| 1 | 6 | 2 |
|-------------------------|
| 2 | 5 | 6 |
|-------------------------|
| 3 | 2 | 1 |
|-------------------------|
| 4 | 3 | 6 |
|-------------------------|
| 5 | 3 | 1 |
|-------------------------|
| 6 | 2 | 2 |
|-------------------------|
| 7 | 4 | 4 |
|-------------------------|
| 8 | 2 | 2 |
|-------------------------|
| 9 | 4 | 3 |
|-------------------------|
| 10 | 1 | 5 |
|-------------------------|
| Total | 32.0 | 32.0 |
---------------------------
Congratulations! Player 2 Wins.

In [12]: # “read” from file and “write”, “add” in file

In [13]: temps = [round([Link](20, 40),1) for i in range(30)]


with open("[Link]", "w") as file: # Auto close
for t in temps:
[Link](f"{t}\n")
print(temps)
print("[Link] file generated with 30 temperature values.")

[39.3, 22.3, 26.7, 35.1, 33.1, 22.6, 25.7, 26.2, 25.8, 37.6, 38.5, 30.7, 36.8, 33.9, 30.6, 37.4, 36.4, 31.9, 2
2.0, 32.4, 28.5, 33.4, 32.3, 32.0, 33.4, 36.1, 39.2, 36.4, 35.8, 21.3]
[Link] file generated with 30 temperature values.

In [14]: #Read a text file ([Link]) containing daily temperature values (one per line).
#Calculate the average temperature and write the result to “[Link]”. File is
#attached.

In [15]: file = open("[Link]","r")


temps = [Link](file)
print(f"Data: {temps}")
average = round([Link](temps),1)
print(f"Average temperature: {average}")
[Link]()

with open("[Link]", "w") as file:


[Link](f"Average Temperature: {average:.2f}°C\n")
print("[Link] file generated.")
Data: [39.3 22.3 26.7 35.1 33.1 22.6 25.7 26.2 25.8 37.6 38.5 30.7 36.8 33.9
30.6 37.4 36.4 31.9 22. 32.4 28.5 33.4 32.3 32. 33.4 36.1 39.2 36.4
35.8 21.3]
Average temperature: 31.8
[Link] file generated.

In [16]: # Read a list of earthquake magnitudes from a file (earthquake_data.txt). Find the
# maximum, minimum, and average magnitude. File is attached.

In [17]: mag = [round([Link](0, 10),1) for i in range(30)]


with open("earthquake_data.txt", "w") as file: # Auto close
for m in mag:
[Link](f"{m}\n")
print(mag)
print("earthquake_data.txt file generated with 30 values.")

[9.9, 7.2, 2.8, 4.7, 8.2, 5.6, 4.3, 7.9, 5.7, 2.3, 0.8, 7.9, 4.4, 2.9, 7.3, 0.4, 2.5, 2.5, 6.3, 6.9, 3.7, 0.3,
8.5, 1.3, 5.8, 0.7, 1.8, 2.3, 2.3, 5.9]
earthquake_data.txt file generated with 30 values.

In [18]: file = open("earthquake_data.txt","r")


mags = [Link](file)
print(f"Data: {mags}")
maximum = round([Link](mags),1)
minimum = round([Link](mags),1)
average = round([Link](mags),1)
print(f"Maximum: {maximum}")
print(f"Minimum: {minimum}")
print(f"Average: {average}")
[Link]()

Data: [9.9 7.2 2.8 4.7 8.2 5.6 4.3 7.9 5.7 2.3 0.8 7.9 4.4 2.9 7.3 0.4 2.5 2.5
6.3 6.9 3.7 0.3 8.5 1.3 5.8 0.7 1.8 2.3 2.3 5.9]
Maximum: 9.9
Minimum: 0.3
Average: 4.4

In [19]: # Read a star catalogue file with names and brightness values ([Link]).
# Filter and save stars brighter than a threshold (e.g., magnitude < 0.1)

In [20]: threshold = 0.1


bright_stars = []

with open("[Link]", "r") as file:


for line in file:
parts = [Link]().split()
if len(parts) == 2:
name, magnitude = parts[0], float(parts[1])
if magnitude > threshold:
bright_stars.append((name, magnitude))
print(bright_stars)
with open("bright_stars.txt", "w") as out:
for name, mag in bright_stars:
[Link](f"{name} {mag}\n")

print("Filtered stars saved to bright_stars.txt")

[('Capella', 0.86), ('Rigel', 0.18), ('Procyon', 0.34), ('Achernar', 0.46), ('Betelgeuse', 0.5), ('Hadar', 0.6
1), ('Altair', 0.77), ('Acrux', 0.76), ('Aldebaran', 0.85), ('Antares', 1.06), ('Spica', 0.97)]
Filtered stars saved to bright_stars.txt

In [21]: # A chemist is monitoring the pH of a solution at different times and recording the
# values in a file ([Link]). Each time a new pH measurement is taken, it is appended to
# the file without overwriting previous data.

In [22]: # A chemist is monitoring the pH of a solution at different times and recording the
# values in a file ([Link]). Each time a new pH measurement is taken, it is appended to
# the file without overwriting previous data.

In [23]: file = open("[Link]", "w")


[Link](f"Hour Min Sec pH \n")

data = input("Entre time and pH in [HH <space> MM <space> SS <space> pH] format")

while([Link]() != "stop"):
parts = [Link]().split()
if len(parts) == 4:
Hour, Minutes, Second, pH = parts[0], parts[1], parts[2], parts[3]
else:
print("data missing...")
print("Re-entre !")
[Link](f"{Hour} {Minutes} {Second} {pH} \n")
data = input("Entre time and pH in [HH <space> MM <space> SS <space> pH] format")
[Link]()

In [24]: file = open("[Link]", "r")


print([Link]())
[Link]()

Hour Min Sec pH


00 00 30 1.2
00 01 00 2.4
00 01 30 3.5
00 02 00 4.7
00 02 30 5.9
00 03 00 7.1

In [25]: # Plotting with matplotlib

In [26]: import [Link] as plt

In [27]: # Write a Python program to plot the function: f(x)= sin(x)*exp(-x^2) for x values in the
# range [-3, 3]. Label the axes and add a title. Make the linewidth 2, linestyle ‘---‘, blue
# color. Save the plot in png format.

In [28]: x = [Link](-3,3,100)
y = ([Link](x))*([Link](-x**2))

[Link](x,y, label="f(x)", color="blue",linewidth=2,linestyle='--')


[Link]("")
[Link]("f(x)")
[Link]("f(x)= sin(x)*exp(-x^2)")
[Link]()
[Link]("[Link]")

<Figure size 640x480 with 0 Axes>

In [29]: # Plot the following functions on the same graph for x in the range [-5, 5],
# give legends, title, x,y labels and save it in a single plot.
# f(x)=x^2 (blue, dashed line)
# g(x)=x^3 (red, solid line)
# h(x)=exp(-x) (green, dotted line)

In [30]: x = [Link](-5, 5, 400)


f = x**2
g = x**3
h = [Link](-x)

[Link](x, f, 'b--', label='f(x) = x²')


[Link](x, g, 'r-', label='g(x) = x³')
[Link](x, h, 'g:', label='h(x) = exp(-x)')
[Link]('x')
[Link]('y')
[Link]('Multiple Functions Plot')
[Link]()
[Link](True)
[Link]('multiple_functions_plot.png')
[Link]()

In [31]: #Write a Python program that reads the following data written in a text file ([Link])
#containing two columns: time (s) and velocity (m/s). Then, plot the velocity vs. time
#graph.

In [32]: data = [Link]("[Link]")


time = data[:, 0]
velocity = data[:, 1]

[Link](time, velocity, 'o-', label='Velocity vs Time')


[Link]('Time (s)')
[Link]('Velocity (m/s)')
[Link]('Velocity vs Time')
[Link]()
[Link](True)
[Link]('velocity_vs_time.png')
[Link]()
In [33]: # (i) Generate a dataset that contains 1000 random Gaussian numbers with mean zero
# and standard deviation “1”, store them in an array. Then, write a Python program to
# plot a histogram with 10 bins and save the plot.

# (ii)Generate another dataset that contains 1000 random Gaussian numbers with mean
# 3 and standard deviation “2”, store them in an array. Plot the histogram with 10 bins
# and save it separately, and compare with the first one.

In [34]: # (1)
data1 = [Link](1000)

mean = 0.0 ; std = 1.0

for i in range(1000):
data1[i] = [Link](mean,std)
#data1[i] = int([Link](1,100))
#print(data1[i])

[Link](data1)
[Link]("mean = 0.0 ; std = 1.0")
[Link]()

# (2)
data2 = [Link](1000)

mean = 3.0 ; std = 2.0

for i in range(1000):
data2[i] = [Link](mean,std)
#data2[i] = int([Link](1,100))
#print(data2[i])

[Link](data2)
[Link]("mean = 3.0 ; std = 2.0")
[Link]()

[Link](data1)
[Link](data2)
[Link]("Comparison between data1 and data2")
[Link]()

You might also like