0% found this document useful (0 votes)
5 views

Lab 01

The document outlines a Python lab for astrophysics, consisting of four exercises. Exercise 1 calculates the factorial of a user-input number, Exercise 2 generates and processes ten random numbers, Exercise 3 plots a mathematical function based on user input, and Exercise 4 visualizes data from a file with points and a connecting line. Each exercise includes code snippets and explanations of the processes involved.

Uploaded by

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

Lab 01

The document outlines a Python lab for astrophysics, consisting of four exercises. Exercise 1 calculates the factorial of a user-input number, Exercise 2 generates and processes ten random numbers, Exercise 3 plots a mathematical function based on user input, and Exercise 4 visualizes data from a file with points and a connecting line. Each exercise includes code snippets and explanations of the processes involved.

Uploaded by

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

Astrophysics Lab

Lab 01 – Python Introduction


Anthony Evans

Exercise 1:

import math

num = int(input("Enter a number to calculate its factorial: "))

f = math.factorial(num)

print("The factorial of", num, " is ", f, ".")

Exercise 2:

import numpy as np
import statistics

x = np.random.uniform(low= 0, high= 1, size=(10)) #Creates an array of 10 random #s

r = np.round(x, 7)
#I rounded to 7 decimal places to get the numbers to display properly in the text file
#When I looked for a solution online, they indicated this can fix it, and it did

sort = sorted(r) #Sorts array in order

mean = statistics.mean(sort) #Provides the mean of the values

meanround = np.round(mean, 7) #To keep things consistent, rounded this to 7 as well

print("The ten random numbers, sorted in ascending order is:")

print(*sort,sep='\n') #prints the sorted values, with each value on a new line

print("\nThe mean value of all 10 numbers is: ", meanround)

np.savetxt("my_array.txt", sort, fmt='%.7f')


#Saves the sorted array to a .txt file, with each value on a new line

print("\nSorted array of values has additionally been saved to 'my_array.txt'")

3. Exercise 3

import numpy as np
import matplotlib.pyplot as plt

whateveryouwant = float(input("For y = 10 - x² + x³/10, enter a value x to find the resulting value


for y: "))
#Not sure if you wanted this also, but since you mentioned this as an input and output,
#I added this too just in case (if you don’t expect this, then just skip to line 15 on)

y = 10 - whateveryouwant**2 + whateveryouwant**3/10
#The y function that the input gets applied to (and is later used for the plot)

y_round = round(y, 7) #Rounds the y value to ensure it prints correctly

print("\nFor x = ", whateveryouwant, ": 10 - ", whateveryouwant, "² + ", whateveryouwant,


"³/10 = ", y_round, sep="")

#Here on redefines whateveryouwant to be the x values for the y values to be plotted

def calculate_y(whateveryouwant):
#creates calculate_y as the function and whateveryouwant as the independent value(s)
y = 10 - whateveryouwant**2 + whateveryouwant**3/10
return y

x_create_values = np.linspace(-5, 5, 101) #Creates the values for the list

x_values = x_create_values.tolist() #Converts the array into a list (since you asked for it as a
"list")

y_values = [] # create empty list to hold y dependent variables as they are calculated

for for_plot in x_values:


y_values.append(calculate_y(for_plot))
#For loop to calculate the values to plot

plt.figure() #New empty list for the values to plot

plt.plot(x_values, y_values, color='magenta') #Plots the x and y values in magenta

plt.xlabel('x')
plt.ylabel('y')

plt.show()

print("\nFor the requested graphed values, see included 'plots'")


Exercise 4

import numpy as np
import matplotlib.pyplot as plt

array = np.loadtxt('01_points.txt') #Loads the file and places it into 'array'

x_values = array[:, 0]
y_values = array[:, 1] #These two lines split the x and y values into two new arrays

plt.figure(figsize=(8, 8)) #Creates the plot with uniform x and y to ensure equal scaling

plt.scatter(x_values, y_values, color='red', s=100, label='Points', zorder=1)


#Plots the points

plt.plot(x_values, y_values, color='blue', linewidth=2, label='Line', zorder=2)


#Plots the line over the points as requested

plt.axis('equal') #Ensures axes are equal as requested

plt.grid(True)
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Points and Connecting Line')
plt.legend()
#The above adds a grid for clarity, labels, and a legend
plt.show()

You might also like