Scientific Programming Lab Manual Final 260225
Scientific Programming Lab Manual Final 260225
A.Y 24-25
LAB CODE: ES353CS
LAB NAME : SCIENTIFIC PROGRAMMING LAB
MANUAL
Compiled from web resources
BY
1.Dr.P.Vishvapathi,DCET
2.Dr.Uma N.Dulhare,MJCET
3.Dr.L.Raghavendar Raju,MECS
1
2
INDEX
SNO CONTENT PAGE NO.
1 Python and MATLAB/GNU OCTAVE installation IDE 4
2 Writing simple Python and MATLAB Programs 5
3 Implementing Control Structures and Functions 8
4 Implementing Data Structures in Python and MATLAB 15
5 Writing and Testing Search and Sort Algorithms 28
6 Analyzing Algorithm Complexity in Practical Problems 33
7 Implementing Numerical Methods in Python and 34
MATLAB
8 Performing Matrix Operations and Solving Linear 39
Systems
9 Case Studies and Applications in Engineering 43
10 Data Manipulation and Analysis using Pandas and 46
MATLAB
11 Creating Various Plots(Line,Scatter,Bar,Histogram) 57
12 Customizing and Interpreting Plots for Engineering 61
Data
13 Implementing Basic Machine Learning Algorithms in 65
Python
14 Exploring IoT and Big Data Tools 70
15 Working on Individual/Group Projects
16 Preparing Project Reports and Presentations 73
17 Final Projection Presentation
3
PROGRAM 1:Python and MATLAB/GNU OCTAVE installation and IDE Setup
Python Installation & IDESetup
a. Installing Python
1. DownloadPython:
o Go to the official Pythonwebsite.
o Download the latest stable version for your operating system
(Windows,macOS, or Linux).
2. Install Python:
o Run the installer.
o On Windows,ensure you select the option "Add Python to
P ATH" during installation (very important).
o Follow the installation prompts for your operating system.
3. Verify Installation:
o Open a terminal(Command Prompt on Windows or Terminal on
macOS/Linux).
o Type python--version(or python3--version on macOS/Linux) to
confirm the installation.
Hello,World!
#Asimpleprogramtoprint"Hello,World!" print("Hello, World!")
OUTPUT: Hello,World!
Factorial of a Number
#A program to find the factorial of a number
num= int(input("Enter a number to find its factorial:"))
factorial = 1
for i in range(1,num+1):
factorial *= i
print(f"The factorial of {num} is {factorial}.")
OUTPUT: Enter a number to find its factorial: 5
The factorial of 5 is 120.
Fibonacci Sequence
#A program to print the Fibonacci sequence up to n terms
n=int(input("Enter the number of terms in the Fibonacci sequence:"))
a, b = 0, 1
print("Fibonacci sequence:")
for _ in range(n):
print(a,end="")
a, b = b, a + b
5
OUTPUT: Enter the number of terms in the Fibonacci sequence: 9
Fibonacci sequence: 0 1 1 2 3 5 8 13 21
Hello,World!
%A simple program to display"Hello,World!"
disp('Hello, World!')
OUTPUT:Hello, World!
Factorial of a Number
%A program to find the factorial of a number
num=input('Enter a number to find its factorial:');
factorial = 1;
fori=1:num
factorial=factorial* i;
end
fprintf('The factorial of %d is %d.\n',num,factorial);
OUTPUT: Enter a number to find its factorial: 5
The factorial of 5 is 120.
6
Fibonacci Sequence
%A program to print the Fibonacci sequence up to n terms
n=input('Enter the number of terms in the Fibonacci sequence:');
a=0;
b=1;
fprintf('Fibonacci sequence:\n'); for
i = 1:n
fprintf('%d',a);
temp = a + b;
a=b;
b=temp;
end
fprintf('\n');
OUTPUT: Enter the number of terms in the Fibonacci sequence: 8
Fibonacci sequence: 0 1 1 2 3 5 8 13
7
PROGRAM 3: Implementing control structures and functions
Python Program Using if-else(Conditional Statement)
8
Python Program Using while Loop : This program counts down from a given
number to zero using a while loop.
This program prints the multiplication table in a grid format using nested loops.
num = int(input("Enter a number to generate its multiplication table: "))
# Using nested for loops to generate the multiplication table
print(f"\nMultiplication Table of {num}:\n")
for i in range(1, 11): # Outer loop for numbers 1 to 10
for j in range(1, 11): # Inner loop for numbers 1 to 10
result = i * j
print(f"{i} x {j} = {result}")
print("-" * 20) # Separating each row for better readability
OUPUT: Enter a number to generate its multiplication table: 5
Multiplication Table of 5:
1x1=1
1x2=2
1x3=3
1x4=4
1x5=5
1x6=6
1x7=7
9
1x8=8
1x9=9
1 x 10 = 10
--------------------
2x1=2
2x2=4
2x3=6
2x4=8
2 x 5 = 10
2 x 6 = 12
2 x 7 = 14
2 x 8 = 16
2 x 9 = 18
2 x 10 = 20
--------------------
...
MATLAB program that demonstrates the use of if-else conditional statements
% Check if the number is positive, negative, or zero
num = input('Enter a number: ');
if num > 0
disp('The number is positive.');
elseif num < 0
disp('The number is negative.');
else
disp('The number is zero.');
end
OUTPUT: Enter a number: 5
The number is positive.
MATLAB program that demonstrates the use of a while loop.
In this example, the program will print numbers from 1 to 10
counter = 1;
% While loop to print numbers from 1 to 10
while counter <= 10
disp(counter);
counter = counter + 1;
% Increment the counter by 1
end
OUTPUT:
1
2
3
4
10
5
6
7
8
9
10
MATLAB program that generates a multiplication table using nested loops:
num = input('Enter a number to generate its multiplication table: ');
% Using nested loops to generate the multiplication table
fprintf('\nMultiplication Table of %d:\n', num);
fori = 1:10 % Outer loop for numbers 1 to 10
forj = 1:10 % Inner loop for numbers 1 to 10
result = i * j;
fprintf('%d x %d = %d\n', i, j, result);
% Print the resultend fprintf('-------------------------\n');
% Separator for better readability
end
OUPUT:
Enter a number to generate its multiplication table: 5
1x1=1
1x2=2
1x3=3
1x4=4
1x5=5
1x6=6
1x7=7
1x8=8
1x9=9
1 x 10 = 10
--------------------
2x1=2
2x2=4
2x3=6
2x4=8
2 x 5 = 10
2 x 6 = 12
2 x 7 = 14
2 x 8 = 16
2 x 9 = 18
2 x 10 = 20
--------------------
...
11
Implementing Functions in Python
12
print(f"Product: {prod}")
OUTPUT: Sum: 12
Difference: 4
Product: 32
14
PROGRAM 4 : Implementing Data Structures in Python and MATLAB
Data Structures in Python
Lists(Array-like Structure) : This program demonstrate to create, update, and
manipulate lists.
#Create a list
fruits=['apple','banana','cherry']
#Add an item to the list
fruits.append('orange')
OUTPUT:
The first fruit is: apple
Fruits from index 1 to 2: ['kiwi', 'cherry']
apple
kiwi
cherry
orange
15
Stack(LIFO:Last In,First Out): Stack Implementation Using a List
class Stack:
def __init__(self): # Fixed: __init__ should be used
self.stack = []
def pop(self):
if self.is_empty():
return "Stack is empty"
return self.stack.pop()
def peek(self):
if self.is_empty():
return "Stack is empty"
return self.stack[-1]
def is_empty(self):
return len(self.stack) == 0
def size(self):
return len(self.stack)
my_stack.push(10)
my_stack.push(20)
my_stack.push(30)
16
Queue(FIFO:First In,First Out)
class Queue:
def __init__(self):
self.queue = [] # Initialize an empty list to represent the queue
def dequeue(self):
"""Remove and return the item from the front of the queue."""
if self.is_empty():
return "Queue is empty"
return self.queue.pop(0) # Remove and return the first item in the list
def peek(self):
"""Return the front item without removing it."""
if self.is_empty():
return "Queue is empty"
return self.queue[0]
def is_empty(self):
"""Check if the queue is empty."""
return len(self.queue) == 0
def size(self):
"""Return the number of items in the queue."""
return len(self.queue)
# Using the Queue
my_queue = Queue()
# Enqueue some items
my_queue.enqueue(10)
my_queue.enqueue(20)
my_queue.enqueue(30)
17
print(f"Front of the queue: {my_queue.peek()}") # The front item should be 10
print(f"Queue size: {my_queue.size()}") # The size should be 3
print(f"Dequeued item: {my_queue.dequeue()}") # It will dequeue 10
print(f"Queue size after dequeue: {my_queue.size()}") # The size will now be 2
print(f"Front of the queue after dequeue: {my_queue.peek()}") # Now it should
be 20
OUTPUT:
Front of the queue: 10
Queue size: 3
Dequeued item: 10
Queue size after dequeue: 2
Front of the queue after dequeue: 20
Here's a simple Python program that demonstrates how to use a dictionary (hash
map) for storing, retrieving, updating, and deleting key-value pairs:
# Create a dictionary
my_dict = {
'name': 'John',
'age': 25,
'city': 'New York'
}
18
my_dict['job'] = 'Engineer'
OUTPUT:
Name: John
Age: 25
City: New York
Updated Dictionary: {'name': 'John', 'age': 26, 'city': 'New York', 'job': 'Engineer'}
Name exists in dictionary: John
19
Removed job: Engineer
Final Dictionary: {'name': 'John', 'age': 26, 'city': 'New York'}
Keys: dict_keys(['name', 'age', 'city'])
Values: dict_values(['John', 26, 'New York'])
% Accessing elements
firstElement = myArray(1); % First element
disp(['First Element: ', num2str(firstElement)]);
% Modifying elements
myArray(2) = 25; % Update the second element
disp('Updated Array:');
disp(myArray); % Output: [10, 25, 30, 40, 50]
% Adding elements
myArray = [myArray, 60]; % Append 60 to the array
disp('Array after Adding 60:');
disp(myArray); % Output: [10, 25, 30, 40, 50, 60]
% Removing elements
myArray(2) = []; % Remove the second element (25)
disp('Array after Removing Second Element:');
disp(myArray); % Output: [10, 30, 40, 50, 60]
% Slicing arrays
subArray = myArray(2:4); % Extract elements 2 to 4
20
disp('Sliced SubArray (2 to 4):');
disp(subArray); % Output: [30, 40, 50]
21
60
methods
% Push an item onto the stack
function push(obj, item)
obj.stack = [obj.stack, item]; % Append item to the end of the stack
end
22
function isEmpty = isEmpty(obj)
isEmpty = isempty(obj.stack); % True if stack is empty, false otherwise
end
23
% Check if the stack is empty
disp(['Is the stack empty? ', num2str(myStack.isEmpty())]); % Output: Is the
stack empty? 0 (false)
24
Queue Implementation in MATLAB
classdef Queue
properties
queue = []; % Initialize an empty array for the queue
end
methods
% Enqueue an item into the queue (add to the end)
function enqueue(obj, item)
obj.queue = [obj.queue, item]; % Append item to the end of the
queue
end
25
isEmpty = isempty(obj.queue); % True if the queue is empty, false
otherwise
end
27
PROGRAM 5: Writing and Testing Search and Sort Algorithms
Search Algorithms in python
Linear Search and Binary Search Algorithm
def linear_search(arr, target):
for index, element in enumerate(arr):
if element == target:
return index # Return the index if the element is found
return -1 # Return -1 if the element is not found
28
# Test Binary Search
binary_result = binary_search(arr_sorted, target)
if binary_result != -1:
print(f"Binary Search: Target {target} found at index {binary_result}")
else:
print(f"Binary Search: Target {target} not found")
OUTPUT:
Linear Search: Target 5 found at index 2
Binary Search: Target 5 found at index 2
for i = 1:length(arr)
if arr(i) == target
index = i; % Return the index (1-based) if element is found
return;
end
end
end
Binary Search in MATLAB
function index = binarySearch(arr, target)
% Binary Search Algorithm (requires sorted array)
% Returns the index of the target element if found, else returns -1
29
while left <= right
mid = floor((left + right) / 2); % Find the middle index
if arr(mid) == target
index = mid; % Return the index (1-based) if the element is found
return;
elseif arr(mid) < target
left = mid + 1; % If the target is larger, search in the right half
else
right = mid - 1; % If the target is smaller, search in the left half
end
end
target = 5;
30
binary_result = binarySearch(arr_sorted, target);
if binary_result ~= -1
disp(['Binary Search: Target ', num2str(target), ' found at index ',
num2str(binary_result)]);
else
disp(['Binary Search: Target ', num2str(target), ' not found']);
end
OUTPUT:
Linear Search: Target 5 found at index 3
Binary Search: Target 5 found at index 3
31
Bubble Sort Algorithm in MATLAB
function sorted_array = bubbleSort(arr)
n = length(arr); % Get the number of elements in the array
for i = 1:n
swapped = false; % Flag to check if any swapping happens
for j = 1:n-i
if arr(j) > arr(j+1)
% Swap elements if they are in the wrong order
temp = arr(j);
arr(j) = arr(j+1);
arr(j+1) = temp;
swapped = true; % Mark that a swap has happened
end
end
% If no elements were swapped, the array is already sorted
if ~swapped
break;
end
end
sorted_array = arr; % Return the sorted array
end
% Example unsorted array
arr = [10, 3, 5, 8, 7, 1, 9, 2];
disp('Original Array:');
disp(arr);
% Call the bubbleSort function
sorted_arr = bubbleSort(arr);
disp('Sorted Array:');
disp(sorted_arr);
OUTPUT:
Original Array:
10 3 5 8 7 1 9 2
Sorted Array:
1 2 3 5 7 8 9 10
32
PROGRAM 6 : Analyzing Algorithm Complexity in Practical Problems
Bubble Sort Time Complexity in python
import time
# Bubble Sort function
def bubble_sort(arr):
n = len(arr)
for i in range(n):
swapped = False # Flag to check if any swap was made during this pass
for j in range(n-i-1): # The last i elements are already sorted
if arr[j] > arr[j+1]:
# Swap elements if they are in the wrong order
arr[j], arr[j+1] = arr[j+1], arr[j]
swapped = True
if not swapped:
break # No swaps were made, array is already sorted
return arr
# Example array
arr = [64, 34, 25, 12, 22, 11, 90]
# Record the start time
start_time = time.time()
# Call the bubble_sort function
sorted_arr = bubble_sort(arr)
# Record the end time
end_time = time.time()
# Calculate the time taken to sort the array
elapsed_time = end_time - start_time
# Output the results
print("Original array:", [64, 34, 25, 12, 22, 11, 90])
print("Sorted array:", sorted_arr)
print(f"Time taken to sort the array: {elapsed_time:.6f} seconds")
OUTPUT:
Original array: [64, 34, 25, 12, 22, 11, 90]
Sorted array: [11, 12, 22, 25, 34, 64, 90]
Time taken to sort the array: 0.000004 seconds
33
PROGRAM 7 : Implementing Numerical Methods in Python and MATLAB
Implementing Numerical Methods in Python
Bisection Method (Root Finding): Let's solve f(x) = x^2 - 4
Let's approximate the integral of f(x) = x^2 from a=0 to b=2 using the Trapezoidal
Rule with n=1000 subintervals.
h = (b - a) / n
return integral * h
def func(x):
return x**2
35
# Applying the Trapezoidal Rule
36
% Example function: f(x) = x^2 - 4
f = @(x) x^2 - 4;
% Using the bisection method
root = bisection_method(f, 0, 3, 1e-5, 100);
disp(['Root: ', num2str(root)]);
OUTPUT: Root: 2
root = x;
end
% Example function: f(x) = x^2 - 4, f'(x) = 2x
f = @(x) x^2 - 4;
f_prime = @(x) 2*x;
% Using the Newton-Raphson method
root = newton_raphson_method(f, f_prime, 3, 1e-5, 100);
disp(['Root: ', num2str(root)]);
OUTPUT: Root: 2
37
integral = 0.5 * (f(a) + f(b)); % First and last terms
for i = 1:n-1
integral = integral + f(a + i * h); % Middle terms
end
integral = integral * h; % Final result
end
% Example function: f(x) = x^2
f = @(x) x^2;
% Using the Trapezoidal Rule
result = trapezoidal_rule(f, 0, 2, 1000);
disp(['Integral result: ', num2str(result)]);
OUTPUT: Integral result: 2.6667
38
PROGRAM 8 : Performing Matrix Operations and Solving Linear Systems
In Python, matrix operations and solving linear systems can be easily performed
using the numpy library.First, ensure that you have numpy installed: pip install
numpy
import numpy as np
# Define matrices
# Matrix Addition
C_add = A + B
# Matrix Subtraction
C_sub = A - B
C_mult = np.dot(A, B)
# Matrix Transpose
C_transpose = A.T
# Matrix Inversion
A_inv = np.linalg.inv(A)
39
OUTPUT:
Matrix Addition:
[[ 6 8]
[10 12]]
Matrix Subtraction:
[[-4 -4]
[-4 -4]]
[[19 22]
[43 50]]
Matrix Transpose of A:
[[1 3]
[2 4]]
Matrix Inverse of A:
[[-2. 1. ]
[ 1.5 -0.5]]
2x + y = 5
x + 2y = 6
40
b = [5, 6]
import numpy as np
b = np.array([5, 6])
x = np.linalg.solve(A, b)
Determinant and Rank of a Matrix: ou can also compute the determinant and
rank of a matrix using numpy.linalg.det() and numpy.linalg.matrix_rank().
# Determinant of matrix A
det_A = np.linalg.det(A)
# Rank of matrix A
rank_A = np.linalg.matrix_rank(A)
Rank of A: 2
41
print("Eigenvalues:", eigenvalues)
print("Eigenvectors:\n", eigenvectors)
Eigenvectors:
[[ 0.70710678 -0.70710678]
[ 0.70710678 0.70710678]]
42
PROGRAM 9 : Case Studies and Applications in Engineering
Steps Involved:
Steps Involved:
Steps Involved:
1. Modeling the System: Create a mathematical model for the motor (e.g.,
transfer function or state-space model).
2. Controller Design: Design a PID controller (Proportional-Integral-Derivative
controller) to regulate motor speed.
3. Simulation: Simulate the system response to step or ramp inputs, and
evaluate performance.
4. Tuning the PID Parameters: Adjust the PID parameters (Kp, Ki, Kd) to
minimize overshoot and settling time.
Steps Involved:
44
1. Filter Design: Design a digital low-pass filter using the Butterworth or
Chebyshev method.
2. Frequency Response Analysis: Analyze the frequency response of the filter
to ensure it meets the desired specifications (e.g., cutoff frequency,
passband ripple).
3. Simulation: Apply the filter to a noisy signal and check the output.
Application: In electrical power systems, load flow analysis (also known as power
flow analysis) is used to determine the voltage, current, power, and impedance at
different points in the network. This helps in understanding how power is
distributed and how the system behaves under different load conditions.
Steps Involved:
45
PROGRAM 10 : Data Manipulation and Analysis using Pandas and MATLAB
import pandas as pd
data = {
# Creating a DataFrame
df = pd.DataFrame(data)
print("Initial DataFrame:")
print(df)
print("\n")
# --- 2. Reading Data from a CSV File (Simulated by creating a DataFrame) ---
print(df['Name'])
print("\n")
46
# Accessing multiple columns
print(df[['Name', 'Age']])
print("\n")
print(df.loc[2])
print("\n")
print(df.iloc[1])
print("\n")
data_with_nan = {
df_nan = pd.DataFrame(data_with_nan)
df_nan['Name'].fillna('Unknown', inplace=True)
df_nan['Age'].fillna(0, inplace=True)
47
print("DataFrame after handling missing values:")
print(df_nan)
print("\n")
data_duplicates = {
df_duplicates = pd.DataFrame(data_duplicates)
df_unique = df_duplicates.drop_duplicates()
print(df_unique)
print("\n")
print(df)
print("\n")
df['Age'] = df['Age'].apply(lambda x: x + 1)
48
print("DataFrame after applying a function to increment the 'Age' column:")
print(df)
print("\n")
grouped_df = df.groupby('City')['Age'].mean()
print(grouped_df)
print("\n")
data2 = {
df2 = pd.DataFrame(data2)
print("Merged DataFrame:")
print(merged_df)
print("\n")
49
# df.to_csv('output.csv', index=False)
OUTPUT:
Initial DataFrame:
Name Age City
0 Alice 25 New York
1 Bob 30 Los Angeles
2 Charlie 35 Chicago
3 David 40 Houston
50
DataFrame after handling missing values:
Name Age City
0 Alice 25 New York
1 Bob 0 Los Angeles
2 Charlie 35 Chicago
3 Unknown 40 Houston
51
New York 26.0
Name: Age, dtype: float64
Merged DataFrame:
Name Age City Age in 5 Years Salary
0 Alice 26 New York 30 50000
1 Bob 31 Los Angeles 35 60000
2 Charlie 36 Chicago 40 70000
3 David 41 Houston 45 80000
disp('Matrix C:');
disp(C);
% 2. Creating a Table
Names = {'Alice', 'Bob', 'Charlie', 'David'};
Ages = [25, 30, 35, 40];
Cities = {'New York', 'Los Angeles', 'Chicago', 'Houston'};
52
T = table(Names', Ages', Cities');
disp('Table of people data:');
disp(T);
53
Age = [25, NaN, 35, 40];
City = {'New York', 'Los Angeles', 'Chicago', 'Houston'};
54
% 7. Saving Data to a CSV File
writetable(T_with_missing, 'people_data.csv');
disp('Data saved to people_data.csv');
Column vector B:
1
2
3
4
5
Matrix C:
1 2 3
4 5 6
7 8 9
First value of A:
1
55
'Alice' 'Bob' 'Charlie' 'David'
56
PROGRAM 11 : Creating Various Plots(Line,Scatter,Bar,Histogram)
# 1. Line Plot
plt.figure(figsize=(10, 6)) # Set the figure size
plt.plot(x, y, label='sin(x)', color='blue') # Line plot for sin(x)
plt.plot(x, y2, label='cos(x)', color='red') # Line plot for cos(x)
plt.title('Line Plot Example')
plt.xlabel('X values')
plt.ylabel('Y values')
plt.legend() # Show legend
plt.grid(True) # Display grid
plt.show()
57
# 2. Scatter Plot
plt.figure(figsize=(10, 6))
plt.scatter(x, y, label='sin(x)', color='green') # Scatter plot for sin(x)
plt.scatter(x, y2, label='cos(x)', color='purple') # Scatter plot for cos(x)
plt.title('Scatter Plot Example')
plt.xlabel('X values')
plt.ylabel('Y values')
plt.legend()
plt.show()
# 3. Bar Plot
plt.figure(figsize=(10, 6))
plt.bar(categories, values, color='orange') # Bar plot
plt.title('Bar Plot Example')
plt.xlabel('Categories')
plt.ylabel('Values')
plt.show()
58
# 4. Histogram
data = np.random.randn(1000) # Generate 1000 random numbers from
normal distribution
plt.figure(figsize=(10, 6))
plt.hist(data, bins=30, color='cyan', edgecolor='black') # Histogram
plt.title('Histogram Example')
plt.xlabel('Data Values')
plt.ylabel('Frequency')
plt.show()
59
60
PROGRAM 12 : Customizing and Interpreting Plots for Engineering Data
plt.figure(figsize=(10, 6))
plt.plot(time, temperature, label='Temperature', color='blue', linestyle='-',
marker='o', markersize=5)
plt.title('Temperature Variation Over 24 Hours', fontsize=14)
plt.xlabel('Time (hours)', fontsize=12)
plt.ylabel('Temperature (°C)', fontsize=12)
plt.grid(True)
plt.legend(loc='upper right')
plt.tight_layout()
plt.show()
plt.figure(figsize=(10, 6))
plt.plot(t, signal, label='Signal', color='red', linestyle='-', linewidth=1.5)
plt.title('Sine Wave Signal (50 Hz)', fontsize=14)
plt.xlabel('Time (seconds)', fontsize=12)
plt.ylabel('Amplitude', fontsize=12)
plt.grid(True, which='both', linestyle='--', color='gray')
plt.legend(loc='upper right')
61
plt.tight_layout()
plt.show()
plt.figure(figsize=(10, 6))
plt.hist(voltage_measurements, bins=30, color='green', edgecolor='black',
alpha=0.7)
plt.title('Histogram of Voltage Measurements', fontsize=14)
plt.xlabel('Voltage (V)', fontsize=12)
plt.ylabel('Frequency', fontsize=12)
plt.grid(True, linestyle='--')
plt.tight_layout()
plt.show()
plt.figure(figsize=(10, 6))
plt.plot(resistance, power, label='Power vs. Resistance', color='purple',
linestyle='-', marker='x')
plt.title('Power vs. Resistance (Ohm’s Law)', fontsize=14)
plt.xlabel('Resistance (Ohms)', fontsize=12)
plt.ylabel('Power (Watts)', fontsize=12)
plt.grid(True, linestyle='-.', color='orange')
plt.legend(loc='upper right')
plt.tight_layout()
plt.show()
62
63
64
PROGRAM 13 : Implementing Basic Machine Learning Algorithms in Python
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error
# Make predictions
y_pred = model.predict(X_test)
65
# Evaluate the model
mse = mean_squared_error(y_test, y_pred)
print(f"Mean Squared Error: {mse}")
Logistic regression is used for binary classification tasks, where the goal is to
predict the probability of a class (e.g., 0 or 1).
# Make predictions
y_pred = log_reg.predict(X_test)
Accuracy: 1.0
Confusion Matrix:
[[17 0]
[ 0 13]]
67
K-Nearest Neighbors (KNN) Example (Supervised Learning)
K-Nearest Neighbors (KNN) is a simple and intuitive algorithm used for both
classification and regression tasks. In this example, we'll use it for classification.
# Make predictions
y_pred = knn.predict(X_test)
Accuracy: 1.0
68
Decision Tree Classifier Example (Supervised Learning)
Decision Trees are used for classification and regression tasks. Here, we'll
implement it for classification.
# Make predictions
y_pred = dt.predict(X_test)
Accuracy: 1.0
69
PROGRAM 14 : Exploring IoT and Big Data Tools
Exploring IoT (Internet of Things) and Big Data Tools can provide insight into
how these technologies work and how they are applied to real-world scenarios.
Both IoT and Big Data are critical components of modern computing, enabling
industries to collect, process, and analyze vast amounts of data in real-time for
better decision-making and automation.
Common IoT Applications:
Smart Homes: Devices like smart thermostats (e.g., Nest), smart lights, and
voice assistants (e.g., Amazon Alexa, Google Assistant).
Wearables: Devices like Fitbit or smartwatches that collect health and
fitness data.
Healthcare: Remote monitoring systems, wearables for health tracking, and
hospital equipment.
Agriculture: Smart farming using IoT-enabled sensors for soil moisture,
temperature, and weather conditions.
Industry 4.0: Industrial IoT (IIoT) sensors and systems that monitor
production lines, machinery, and energy consumption.
IoT Tools
Several platforms and tools are available to work with IoT systems. These tools
facilitate the deployment, management, and integration of IoT devices.
70
IoT Protocols
71
Apache Hive: A data warehouse system built on top of Hadoop for querying
and managing large datasets.
Apache Pig: A platform for analyzing large datasets that provide a high-level
scripting language.
PrestoDB: A distributed SQL query engine designed for running interactive
analytic queries on large datasets.
Tableau: A powerful data visualization tool that helps in creating interactive
and shareable dashboards to analyze Big Data.
Power BI: Microsoft’s business analytics service that allows for data
visualization and sharing insights from Big Data.
The integration of IoT and Big Data plays a significant role in industries like
manufacturing, healthcare, and smart cities, where IoT devices collect massive
amounts of data that need to be processed and analyzed for real-time decision-
making. Here are some ways these technologies work together:
Data Collection via IoT Devices: Sensors and IoT devices collect real-time
data (e.g., from manufacturing machines, smart home devices, or wearable
health devices).
Data Streaming and Processing: The data is sent to cloud platforms (e.g.,
AWS IoT, Google Cloud IoT) or to Big Data platforms like Apache Kafka or
Apache Flink for real-time processing.
Big Data Storage: The processed data is stored in Big Data platforms such as
Hadoop, HBase, or NoSQL databases like MongoDB.
Analytics and Insights: Advanced analytics using tools like Apache Spark,
Presto, or machine learning models to gain insights from the data. These
insights are then used for decision-making, predictive maintenance, or
anomaly detection.
72
PROGRAM 15 : Working on Individual/Group Projects
PROGRAM 16 : Preparing Project Reports and Presentations
PROGRAM 17 : Final Projection Presentation
Working on individual or group projects using scientific programming can be
both rewarding and challenging. It provides an opportunity to apply
mathematical and computational techniques to solve real-world problems.
These projects often involve using programming languages such as Python,
MATLAB, R, or other domain-specific languages that facilitate mathematical
modeling, data analysis, and simulation. Below are some general steps and
considerations for working on these types of projects.
1. Defining the Project
Whether you're working alone or in a group, the first step is defining the project's
scope and objectives clearly. This is where you decide the problem you are trying
to solve, which data or systems you need to work with, and what tools and
methods you will use.
For many scientific programming projects, the first step is collecting and preparing
73
data. Data might come from sensors, databases, simulations, or online resources.
Steps to follow:
Data Collection: Ensure the data you're collecting is reliable and relevant to
your problem. For instance, if you're working on environmental modeling,
you might collect data from sensors or databases related to temperature,
humidity, air quality, etc.
Data Cleaning: Raw data often needs preprocessing. This includes removing
outliers, filling missing values, normalizing, and transforming the data into a
usable format.
Data Storage: Organize your data properly in files (CSV, JSON, etc.) or
databases (SQL, NoSQL).
3. Algorithm Development
Once you have your data, the next step is to develop algorithms to analyze,
process, or model the data. This could involve implementing numerical methods,
optimization techniques, machine learning models, etc.
Examples of algorithms:
Numerical Methods:
o Solving linear systems of equations (using Gaussian elimination, LU
decomposition).
o Optimization techniques (gradient descent, Newton-Raphson
method).
o Interpolation and integration (e.g., Newton's interpolating polynomial
or Simpson's rule for numerical integration).
Machine Learning:
o Supervised Learning: Implement regression (linear regression,
decision trees) or classification (SVM, KNN, neural networks).
o Unsupervised Learning: Clustering algorithms like k-means,
hierarchical clustering, or dimensionality reduction techniques like
PCA.
Simulation:
o For example, simulating a physical process like projectile motion or
circuit behavior (using methods such as Monte Carlo simulations or
finite element analysis).
4. Visualization
74
programming projects often require you to plot graphs, charts, or 3D
visualizations.
Python:
o Matplotlib: For creating 2D graphs and plots.
o Seaborn: Built on top of Matplotlib for advanced statistical plotting.
o Plotly: For interactive visualizations.
o Mayavi/Plotly: For 3D visualizations.
MATLAB:
o Built-in functions such as plot, surf, mesh, etc., allow for 2D and 3D
plotting.
Once the algorithm is implemented, you must test and validate it to ensure it
works as expected. This involves:
Unit Testing: Testing individual parts of the code to check their correctness.
Integration Testing: Verifying if different parts of the system work well
together.
Validation: Comparing your results with real-world data or known
benchmarks.
For both individual and group projects, proper documentation is crucial. This
includes:
75
7. Collaboration (for Group Projects)
These steps will help ensure that your scientific programming project is well-
executed and produces meaningful, interpretable results.
76