Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
3 views

ENGR1330-Assignment5

The document contains an assignment with four questions focused on using NumPy for array manipulation, matrix operations, numerical methods for finding roots, and simulating heat conduction using the finite difference method. Each question includes specific tasks and code examples to guide the implementation. The assignment aims to assess understanding of NumPy functionalities and numerical analysis techniques.

Uploaded by

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

ENGR1330-Assignment5

The document contains an assignment with four questions focused on using NumPy for array manipulation, matrix operations, numerical methods for finding roots, and simulating heat conduction using the finite difference method. Each question includes specific tasks and code examples to guide the implementation. The assignment aims to assess understanding of NumPy functionalities and numerical analysis techniques.

Uploaded by

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

Assignment-5 (100 points)

Anthony, James

R#11937991

# RUN this cell and do not modify it


import sys
! hostname
! whoami
print(sys.executable)
print(sys.version)
print(sys.version_info)

DESKTOP-LKKK32J
desktop-lkkk32j\ja606
C:\Users\ja606\anaconda3\python.exe
3.12.4 | packaged by Anaconda, Inc. | (main, Jun 18 2024, 15:03:56) [MSC v.1929 64 bit (AMD64)]
sys.version_info(major=3, minor=12, micro=4, releaselevel='final', serial=0)

Question 1 (20 pts): NumPy Playground


The core datatype of NumPy is the NumPy Array. NumPy Arrays build on the basic Python List
datatype to add functionality for vector math and common statistical calculations. The easiest
way to create a NumPy Array is to first create a List and then passing it as the argument to the
np.Array() constructor. In this exercise, you'll create some NumPy arrays, and then perform
some simple operations on them.

Resources
https://www.w3schools.com/PYTHON/numpy/numpy_creating_arrays.asp
https://www.w3schools.com/PYTHON/numpy/numpy_array_shape.asp
https://www.w3schools.com/PYTHON/numpy/numpy_array_sort.asp

Instructions
1. Create a 1-dimensional Array, named my_arr containing the elements [9,8,7,6,5,4,3,2,1].
2. Print the shape of my_arr.
3. Create a 2-dimensional Array, named my_mat containing rows, each containing a copy of my_arr.
4. Print the shape of my_mat.
5. Create a new Array named my_prod and use it to store the result of the operation my_arr * my_arr.
6. Print out my_prod
7. Use the np.sort function to sort my_prod and store the result in a new Array named my_prod_sorted.
8. Print out my_prod_sorted

# Question 1 Code Goes Here


import numpy as np
my_arr = np.array([9, 8, 7, 6, 5, 4, 3, 2, 1])
print("Shape of my_arr:", my_arr.shape)
my_mat = np.tile(my_arr, (3, 1))
print("Shape of my_mat:", my_mat.shape)
my_prod = my_arr * my_arr
print("my_prod:", my_prod)
my_prod_sorted = np.sort(my_prod)
print("my_prod_sorted:", my_prod_sorted)

Shape of my_arr: (9,)


Shape of my_mat: (3, 9)
my_prod: [81 64 49 36 25 16 9 4 1]
my_prod_sorted: [ 1 4 9 16 25 36 49 64 81]

Question 2 (20 pts) Matrices:


NumPy really shines when it's time to work with vectors and matrices. A lot of complex
operations work right out of the box and are very easy to use. In this exercise, we'll look at how
to manipulate the shape of matrices, access their rows and columns, and perform some matrix
math operation
https://www.w3schools.com/PYTHON/numpy/numpy_array_reshape.asp
https://www.w3schools.com/PYTHON/numpy/numpy_array_indexing.asp
https://pythonexamples.org/python-numpy-dot-product/

1. In Question 2, you created an array called my_arr. Use the reshape function to create a 3x3 matrix named arr_reshaped.
2. Print out arr_reshaped to see the result.
3. Use indexing to print out the last row of the matrix and print out the element at the center of the matrix.
4. Create two 1-dimensional arrays named X and Y with the elements [3,9,5,4] and [1,8,7,6], respectively.
5. Compute the dot product of X and Y and print the result.

import numpy as np

my_arr = np.array([9, 8, 7, 6, 5, 4, 3, 2, 1])


arr_reshaped = my_arr.reshape(3, 3)
print("arr_reshaped:\n", arr_reshaped)

last_row = arr_reshaped[-1]
print("Last row:", last_row)

center_element = arr_reshaped[1, 1]
print("Element at the center:", center_element)

X = np.array([3, 9, 5, 4])
Y = np.array([1, 8, 7, 6])

dot_product = np.dot(X, Y)
print("Dot product of X and Y:", dot_product)

arr_reshaped:
[[9 8 7]
[6 5 4]
[3 2 1]]
Last row: [3 2 1]
Element at the center: 5
Dot product of X and Y: 134

Question 3 (20 pts):


Find the root of the function y(x) = x 3 − 2x − 5x using the bisection method and the secant method. Plot the function and the
approximations from both methods.

# Question 3 Code Bisection Goes Here


import numpy as np
def f(x):
return x**3 - 7*x
def bisection(a, b, tol=1e-6, max_iter=100):
iter_count = 0
while (b - a) / 2 > tol:
c = (a + b) / 2
if f(c) == 0:
return c
elif f(a) * f(c) < 0:
b = c
else:
a = c
iter_count += 1
if iter_count > max_iter:
break
return (a + b) / 2

a, b = -3, 3
root_bisection = bisection(a, b)
print(f"Root from Bisection Method: {root_bisection}")

Root from Bisection Method: 0.0

# Question 3 Code Secant Goes Here


import numpy as np

def f(x):
return x**3 - 7*x

def secant(x0, x1, tol=1e-6, max_iter=100):


iter_count = 0
while abs(x1 - x0) > tol:
x_new = x1 - f(x1) * (x1 - x0) / (f(x1) - f(x0))
x0, x1 = x1, x_new
iter_count += 1
if iter_count > max_iter:
break
return x1

x0, x1 = -3, 3
root_secant = secant(x0, x1)
print(f"Root from Secant Method: {root_secant}")

Root from Secant Method: 0.0

Question 4 (20 pts):


You will simulate heat conduction along a metal rod using the finite difference method. The goal is to observe how the temperature
evolves over time.

Given:
Length of the rod (L): 1 meter
Initial temperature distribution: Uniform at 100°C
Boundary conditions:
(u(0, t) = 100) °C (left end)
(u(L, t) = 0) °C (right end)
Total simulation time (T): 1 second
Spatial step ( Delta x): 0.1 m
Time step ( Delta t): 0.01 s
Thermal diffusivity (alpha): 0.1 m²/s

Tasks
1. Initialize the temperature distribution along the rod.

2. Use the explicit finite difference method to update the temperature at each time step.

3. Apply the boundary conditions at each time step.

4. Visualize the temperature distribution at selected time intervals.

Use the below example code as an outline for your code

# EXAMPLE CODE STRUCTURE- USe it to write yor own below


import numpy as np
import matplotlib.pyplot as plt

# Parameters
L = 1.0 # Length of the rod
alpha = 0.1 # Thermal diffusivity
T = 1.0 # Total time
dx = 0.1 # Spatial step
dt = 0.01 # Time step

# Discretization
x = np.arange(0, L + dx, dx)
Nx = len(x)
time_steps = int(T / dt)

# Initial condition
u = np.ones(Nx) * 100 # Initial temperature: 100°C

# Finite difference method


for n in range(time_steps):
u_new = np.copy(u)
for i in range(1, Nx - 1):
u_new[i] = u[i] + alpha * dt / dx**2 * (u[i-1] - 2*u[i] + u[i+1])

# Apply boundary conditions


u_new[0] = 100 # Left end
u_new[-1] = 0 # Right end

u = u_new

# Visualization (plot every 10 steps)


if n % 10 == 0:
plt.plot(x, u, label=f'Time = {n*dt:.2f}s')
# Final plot settings
plt.title('Temperature Distribution along the Rod')
plt.xlabel('Position along the rod (m)')
plt.ylabel('Temperature (°C)')
plt.legend()
plt.grid()
plt.show()

Processing math: 100%

You might also like