0% found this document useful (0 votes)
17 views15 pages

ENEL2CM Assignment 2 (2025)

This document contains a series of programming assignments related to applied computer methods, focusing on data manipulation using Python libraries such as NumPy, SymPy, and Pandas. It includes tasks like calculating statistical measures, performing differentiation and integration, managing file operations, and creating data visualizations. The assignments also involve handling chemical reaction data and generating CSV files for analysis.

Uploaded by

owethuhandsome03
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)
17 views15 pages

ENEL2CM Assignment 2 (2025)

This document contains a series of programming assignments related to applied computer methods, focusing on data manipulation using Python libraries such as NumPy, SymPy, and Pandas. It includes tasks like calculating statistical measures, performing differentiation and integration, managing file operations, and creating data visualizations. The assignments also involve handling chemical reaction data and generating CSV files for analysis.

Uploaded by

owethuhandsome03
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/ 15

APPLIED COMPUTER METHODS

ENEL2CM

ASSIGNMENT 2

OWETHU DLUDLA

221006252

28 MARCH 2025
1|Page
QUESTION 1

a) import numpy as np
# Store the yields in a NumPy array

yields = np.array([50, 55, 49, 48, 52])

print("Yields recorded in mg:", yields)

b) import numpy as np
# Calculate and print the mean, standard deviation, and variance

yields = np.array ([50, 55, 49, 48, 52])

print("Yields recorded in mg:", yields)

mean_yield = np.mean(yields)

std_dev = np.std(yields)

variance = np.var(yields)

print(f"Mean yield: {mean_yield:.2f} mg")

print(f"Standard deviation: {std_dev:.2f} mg")

print(f"Variance: {variance:.2f} mg²")

2|Page
c) import numpy as np
# Scale the yields up by a factor of 1.1

yields = np.array ([50, 55, 49, 48, 52])

scaled_yields = yields * 1.1

print("Scaled yields:", scaled_yields)

3|Page
d) import numpy as np

yields = np.array ([50, 55, 49, 48, 52])

mean_yield = 50.80

above_mean = yields[yields > mean_yield]

print("Trials yielding above mean:", above_mean)

QUESTION 2

a) from sympy import symbols, diff, integrate, cos

x = symbols('x')

f = (x**2 + 1) * cos(x)

differential_f = diff(f, x)

print("Differential of f(x):", differential_f)

integration_f = integrate(f, x)

print("Integration of f(x):", integration_f)

4|Page
b) from sympy import symbols, diff, cos

x = symbols('x')

f = (x**2 + 1) * cos(x)

# Compute the differential of f(x)

differential = diff(f, x)

# Ask the user for the value of x

x_value = float(input("Enter the value of x: "))

# Evaluate the differential equation at the user-specified value of x

result = differential.subs(x, x_value)

# Print the result in a readable format

print(f"The differential equation f(x) at x = {x_value} is {result}")

5|Page
c) from sympy import symbols, integrate, cos

x = symbols('x')

f = (x**2 + 1) * cos(x)

# Compute the integration of f(x) from x=0 to x=2

integration_result = integrate(f, (x, 0, 2))

# Print the result in a readable format

print(f"The integration of f(x) from x=0 to x=2 is: {integration_result}")

6|Page
d) from sympy import symbols, diff, integrate, cos

import matplotlib.pyplot as plt

import numpy as np

x = symbols('x')

f = (x**2 + 1) * cos(x)

df_dx = diff(f, x)

int_f = integrate(f, x)

x_vals = np.linspace(0, 2, 100)

f_lambda = lambda x_val: (x_val**2 + 1) * np.cos(x_val)

f_vals = [f_lambda(x_val) for x_val in x_vals]

plt.figure(figsize=(10, 6))

plt.plot(x_vals, f_vals, label='f(x) = (x^2 + 1) * cos(x)', color='b')

plt.xlabel('x')

plt.ylabel('f(x)')

plt.title('Plot of f(x) = (x^2 + 1) * cos(x)')

plt.legend()

plt.grid(True)

plt.show()

7|Page
QUESTION 3

a) # List of chemical substances and their quantities

inventory = [

("Water", 100),

("Sodium chloride", 50),

("Acetone", 75),

("Sulfuric acid", 20),

("Ethanol", 60)

# Open the file in write mode (this will create the file if it doesn't exist)

with open("inventory.txt", "w") as file:

# Iterate through the inventory list and write each substance and quantity

for substance, quantity in inventory:

file.write(f"{substance}, {quantity}\n")

print("inventory.txt has been created and populated with substances.")

8|Page
b) # Open the file in read mode

with open("inventory.txt", "r") as file:

# Read the contents of the file

contents = file.read()

# Print the contents

print(contents)

c) # New substance to add to the inventory

new_substance = "Sodium Chloride, 500g"

# Open the file in append mode to add to the end of the file

with open("inventory.txt", "a") as file:

# Write the new substance to the file

file.write(new_substance + "\n")

print(f"{new_substance} has been added to inventory.txt.")

9|Page
d) # Define the name of the inventory file

inventory_file = "inventory.txt"

new_substance = "Sodium Chloride, 500g"

# Define the name of the inventory file

inventory_file = "inventory.txt"

new_substance = "Sodium Chloride, 500g"

try:

# Attempt to open the inventory file in append mode

with open(inventory_file, 'a') as file:

# Write the new substance to the file

file.write(new_substance + "\n")

print(f"{new_substance} has been added to the inventory.")

# Reopen the file in read mode to print its contents

with open(inventory_file, 'r') as file:

lines = file.readlines()

10 | P a g e
print("\nContents of the inventory file:")

for line in lines:

print(line.strip())

except FileNotFoundError:

# Handle the case where the file does not exist

print(f"Error: File '{inventory_file}' not found.")

except Exception as e:

# Handle any other exceptions

print(f"An error occurred: {e}")

11 | P a g e
QUESTION 4

a) import pandas as pd

#Create the dataset with columns 'Reaction', 'Reactant_A_Moles',


'Reactant_B_Moles', and 'Product_Yield_Percentage'

data = {

'Reaction': ['Reaction_1', 'Reaction_2', 'Reaction_3', 'Reaction_4', 'Reaction_5',

'Reaction_6', 'Reaction_7', 'Reaction_8', 'Reaction_9', 'Reaction_10'],

'Reactant_A_Moles': [1.5, 2.3, 0.9, 1.2, 2.0,

3.0, 1.8, 2.5, 1.0, 2.8],

'Reactant_B_Moles': [0.8, 1.5, 1.2, 1.0, 1.6,

2.2, 1.4, 1.9, 0.7, 1.3],

'Product_Yield_Percentage': [75, 85, 90, 80, 95,

88, 92, 87, 78, 82]

#Create the dataframe

df = pd.DataFrame(data)

#Save the dataframe to a CSV file

df.to_csv('reactions.csv', index=False)

#Load the CSV file using Pandas

df_loaded = pd.read_csv('reactions.csv')

#Display the loaded dataframe

print(df_loaded)

12 | P a g e
b) import pandas as pd

#Load the CSV file using Pandas (from previous question)

df_loaded = pd.read_csv('reactions.csv')

#Calculate the average yield percentage

average_yield = df_loaded['Product_Yield_Percentage'].mean()

#Print the average yield percentage

print(f"The average yield percentage for all reactions is: {average_yield:.2f}%")

13 | P a g e
c) import pandas as pd

#Load the CSV file using Pandas (from previous question)

df_loaded = pd.read_csv('reactions.csv')

#Calculate and print descriptive statistics for the "Product_Yield_Percentage"

yield_statistics = df_loaded['Product_Yield_Percentage'].describe()

#Print the descriptive statistics

print("Descriptive statistics for the yield percentage:")

print(yield_statistics)

d) import pandas as pd

#Load the CSV file using Pandas (assuming the CSV file already exists)

df_loaded = pd.read_csv('reactions.csv')

#Filter the dataset to include only reactions with high efficiency (e.g., yield
percentage >= 90)

high_efficiency_df = df_loaded[df_loaded['Product_Yield_Percentage'] >= 90]

#Save the filtered data to a new CSV file

high_efficiency_df.to_csv('high_efficiency_reactions.csv', index=False)
14 | P a g e
#Print the filtered dataset (optional)

print("Filtered dataset with high efficiency reactions:")

print(high_efficiency_df)

15 | P a g e

You might also like