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

PythonforScientificComputing AEC QuestionBank

The document discusses writing Python programs to perform various statistical analyses and matrix operations on datasets. It provides examples to calculate statistics, fit curves, compress images using SVD, and plot multiple functions on the same graph using data from Excel files.

Uploaded by

abhijitsahydri
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

PythonforScientificComputing AEC QuestionBank

The document discusses writing Python programs to perform various statistical analyses and matrix operations on datasets. It provides examples to calculate statistics, fit curves, compress images using SVD, and plot multiple functions on the same graph using data from Excel files.

Uploaded by

abhijitsahydri
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

DEPARTMENT OF MECHANICAL ENGINEERING

21ME38/ 21AR38 - Python for Scientific Computing


Question Bank – SEE Lab Exam
1 Write a program to calculate the mean, median, variance, maximum, minimum,
range and standard deviation of a set of numbers in a file named data.txt.
Save the script file as statistic_test.py

import numpy as np

# Open the file and read the data


with open("data.txt", "r") as file:
data = file.read().split(",")

# Convert the data to a NumPy array of floats


data = np.array([float(x) for x in data])

# Calculate the mean, median, variance, maximum, minimum, range, and standard
deviation
mean = np.mean(data)
median = np.median(data)
variance = np.var(data)
maximum = np.max(data)
minimum = np.min(data)
range_ = maximum - minimum
std_dev = np.std(data)

# Print the results


print("Mean:", mean)
print("Median:", median)
print("Variance:", variance)
print("Maximum:", maximum)
print("Minimum:", minimum)
print("Range:", range_)
print("Standard deviation:", std_dev)

2 Write a python Program to calculate the mean, median, variance, maximum,


minimum, range and standard deviation of a set of numbers in a file named
data.xlsx

import pandas as pd
import numpy as np

# Read the Excel file into a Pandas data frame


df = pd.read_excel("data.xlsx")

# Extract the column of data

1|Page
data = df["Data"].values

# Calculate the mean, median, variance, maximum, minimum, range, and standard
deviation
mean = np.mean(data)
median = np.median(data)
variance = np.var(data)
maximum = np.max(data)
minimum = np.min(data)
range_ = maximum - minimum
std_dev = np.std(data)

# Print the results


print("Mean:", mean)
print("Median:", median)
print("Variance:", variance)
print("Maximum:", maximum)
print("Minimum:", minimum)
print("Range:", range_)
print("Standard deviation:", std_dev)

3 Write a python program to calculate the eigenvalue and eigenvectors of a matrix


[[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]

import numpy as np

# Define the matrix


matrix = np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]])

# Calculate the eigenvalues and eigenvectors


eigenvalues, eigenvectors = np.linalg.eig(matrix)

# Print the results


print("Eigenvalues:", eigenvalues)
print("Eigenvectors:")
for i in range(len(eigenvectors)):
print(eigenvectors[:,i])

4 Write a python program to calculate the Inverse of a matrix


[[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]

import numpy as np

# Define the matrix


matrix = np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]])

# Calculate the inverse

2|Page
inverse = np.linalg.inv(matrix)

# Print the result


print(inverse)

5 Write a python program to do linear curve fitting for a given set of x and y
values in data.xlsx file

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

# Read the Excel file into a Pandas dataframe


df = pd.read_excel("data.xlsx")

# Extract the columns of x and y values


x = df["X"].values
y = df["Y"].values

# Perform linear curve fitting


slope, intercept = np.polyfit(x, y, 1)

# Create a plot of the data and the linear fit


plt.scatter(x, y, label="Data")
plt.plot(x, slope*x + intercept, color="red", label="Linear Fit")
plt.xlabel("X")
plt.ylabel("Y")
plt.title("Linear Curve Fitting")
plt.legend()
plt.show()

# Print the equation of the linear fit


print("Equation of the linear fit: y = {}x + {}".format(slope, intercept))

6 Write a python program to compress an image file image.png by matrix


manipulation using Singular Value Decomposition. Use only numpy and
matplotlib library only

In this program, we first load the image file into a NumPy array using the imread()
function from Matplotlib. We then convert the image array to grayscale by taking the
mean value along the third axis (corresponding to the color channels).

We perform Singular Value Decomposition (SVD) on the grayscale image array


using the linalg.svd() function from NumPy. The resulting U, S, and V arrays
represent the left singular vectors, singular values, and right singular vectors.

3|Page
We choose a rank value for compression and set all singular values beyond this rank
value to zero. Using matrix multiplication, we then reconstruct the compressed image
from the compressed singular values.

Finally, we save the compressed image as a new file using the imsave() function from
Matplotlib. We also show the original and compressed images side by side using
Matplotlib's subplots() function.

import numpy as np
import matplotlib.pyplot as plt

# Load the image file into a NumPy array


img = plt.imread("image.png")

# Convert the image array to grayscale


img_gray = np.mean(img, axis=2)

# Perform Singular Value Decomposition (SVD)


U, S, V = np.linalg.svd(img_gray)

# Choose the rank for compression


rank = 50

# Compress the image by keeping only the first 'rank' singular values
S[rank:] = 0

# Reconstruct the compressed image from the compressed singular values


img_compressed = np.dot(U, np.dot(np.diag(S), V))

# Save the compressed image as a new file


plt.imsave("compressed_image.png", img_compressed, cmap="gray")

#optional
# Show the original and compressed images side by side
fig, axs = plt.subplots(1, 2)
axs[0].imshow(img_gray, cmap="gray")
axs[0].set_title("Original Image")
axs[1].imshow(img_compressed, cmap="gray")
axs[1].set_title("Compressed Image (Rank {})".format(rank))
plt.show()

7 Write a python program to extract X and y data from excel and plot the
following functions as subplots (i) y=2sin(x)- x^2 (ii) y= x^3 + 3x+5 (iii) y =7^x
+8x+1

In this program, we first read the Excel file "data.xlsx" into a Pandas dataframe and
extract the columns of X and y values using the values attribute.

4|Page
We define three functions to plot: function1(x) which calculates y=2sin(x)-x^2,
function2(x) which calculates y=x^3+3x+5, and function3(x) which calculates
y=7^x+8x+1.

We create a subplot figure with three rows and one column using the subplots()
function from Matplotlib. We plot each function as a line plot on its own subplot
using the plot() function. We also plot the original data as blue dots on each subplot.
We add appropriate axis labels, titles, and legends to each subplot.

Finally, we use the tight_layout() function to improve the spacing between subplots
and show the plot using plt.show().

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

# Read the Excel file into a Pandas dataframe


df = pd.read_excel("data.xlsx")

# Extract the columns of X and y values


X = df["X"].values
y = df["Y"].values

# Define the three functions to plot


def function1(x):
return 2*np.sin(x) - x**2

def function2(x):
return x**3 + 3*x + 5

def function3(x):
return 7**x + 8*x + 1

# Create the subplot figure


fig, axs = plt.subplots(3, 1, figsize=(8, 12))

# Plot the first function


axs[0].plot(X, y, color="blue", label="Data")
axs[0].plot(X, function1(X), color="red", label="y=2sin(x)-x^2")
axs[0].set_xlabel("X")
axs[0].set_ylabel("y")
axs[0].set_title("Function 1")
axs[0].legend()

# Plot the second function


axs[1].plot(X, y, color="blue", label="Data")
axs[1].plot(X, function2(X), color="red", label="y=x^3+3x+5")

5|Page
axs[1].set_xlabel("X")
axs[1].set_ylabel("y")
axs[1].set_title("Function 2")
axs[1].legend()

# Plot the third function


axs[2].plot(X, y, color="blue", label="Data")
axs[2].plot(X, function3(X), color="red", label="y=7^x+8x+1")
axs[2].set_xlabel("X")
axs[2].set_ylabel("y")
axs[2].set_title("Function 3")
axs[2].legend()

# Show the plot


plt.tight_layout()
plt.show()

8 Write a python program to extract X and y data from excel and plot the
following functions in a single plot (i) y=2sin(x)- x^2 (ii) y= x^3 + 3x+5 (iii) y
=7^x +8x+1 as red dot, black star and blue diamond respectively

In this program, we first use the Pandas read_excel() function to read the Excel file
"data.xlsx" into a dataframe. We then extract the columns of x and y values from the
dataframe using the values attribute.

We define the three functions to plot (function1(), function2(), and function3()), and
evaluate each of them for the given x values using NumPy. We then plot the three
functions in a single plot using Matplotlib's plot() function. We use the 'ro', 'k*', and
'bd' format strings to plot the functions as red dots, black stars, and blue diamonds,
respectively. We also use the label argument to provide Latex-formatted legend for
each function.

Finally, we add axis labels and a plot title using Matplotlib's xlabel(), ylabel(), and
title() functions, and add the legend to the plot using the legend() function with the
loc argument set to 'upper left'

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

# Read the Excel file into a Pandas dataframe


df = pd.read_excel("data.xlsx")

# Extract the columns of x and y values


x = df["X"].values
y = df["Y"].values

# Define the three functions to plot

6|Page
def function1(x):
return 2*np.sin(x) - x**2

def function2(x):
return x**3 + 3*x + 5

def function3(x):
return 7**x + 8*x + 1

# Evaluate the functions for the given x values


y1 = function1(x)
y2 = function2(x)
y3 = function3(x)

# Plot the three functions in a single plot


plt.plot(x, y1, 'ro', label=r'$y=2\sin(x)-x^2$')
plt.plot(x, y2, 'k*', label=r'$y=x^3+3x+5$')
plt.plot(x, y3, 'bd', label=r'$y=7^x+8x+1$')
plt.xlabel("X")
plt.ylabel("Y")
plt.title("Three Functions Plot")
plt.legend(loc='upper left')
plt.show()

9 Write a Program to calculate the cross-product and dot product of two vectors

In this program, we first define the two vectors as NumPy arrays. We then calculate
the cross product of the two vectors using the cross() function from NumPy, and store
the result in the cross_product variable. We print out the cross product using the
print() function.

We also calculate the dot product of the two vectors using the dot() function from
NumPy, and store the result in the dot_product variable. We print out the dot product
using the print() function.

import numpy as np

# Define the two vectors


vector1 = np.array([1, 2, 3])
vector2 = np.array([4, 5, 6])

# Calculate the cross product of the two vectors


cross_product = np.cross(vector1, vector2)
print("Cross product:", cross_product)

# Calculate the dot product of the two vectors


dot_product = np.dot(vector1, vector2)
print("Dot product:", dot_product)

7|Page
10 Write a program to find the lcm and hcf of three numbers using only the math
library

In this program, we first define the three numbers as variables num1, num2, and
num3.

We calculate the HCF of the three numbers using the gcd() function from the math
module. We use the gcd() function twice, first to calculate the GCD of num1 and num2,
and then to calculate the GCD of the result and num3. The final result is stored in the
hcf variable, which we print using the print() function.

We calculate the LCM of the three numbers using the formula LCM =
|num1*num2*num3| / HCF, where |num1*num2*num3| represents the absolute value
of the product of the three numbers. We calculate the absolute value using the abs()
function. As shown above, we divide the product by the HCF of the three numbers,
which we calculate using the gcd() function. The final result is stored in the lcm
variable, which we print using the print() function.

import math

# Define the three numbers


num1 = 12
num2 = 18
num3 = 24

# Calculate the HCF of the three numbers


hcf = math.gcd(math.gcd(num1, num2), num3)
print("HCF:", hcf)

# Calculate the LCM of the three numbers


lcm = abs(num1*num2*num3) // math.gcd(math.gcd(num1, num2), num3)
print("LCM:", lcm)

8|Page

You might also like