0% found this document useful (0 votes)
4 views51 pages

PS&LP Practical File

The document outlines a series of experiments conducted using Scilab, focusing on matrix operations, classification of numbers, average calculation, and Fibonacci sequence generation. Each experiment includes objectives, relevant course outcomes, apparatus used, theoretical background, Scilab code, results, inferences, and precautions. The experiments aim to enhance understanding of programming concepts and mathematical operations through practical implementation.

Uploaded by

sanyamnagpal35
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)
4 views51 pages

PS&LP Practical File

The document outlines a series of experiments conducted using Scilab, focusing on matrix operations, classification of numbers, average calculation, and Fibonacci sequence generation. Each experiment includes objectives, relevant course outcomes, apparatus used, theoretical background, Scilab code, results, inferences, and precautions. The experiments aim to enhance understanding of programming concepts and mathematical operations through practical implementation.

Uploaded by

sanyamnagpal35
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

Experiment No.

1
Experiment Title
Installation of Scilab and demonstration of basic matrix operations (Addition, Subtraction,
Multiplication, Division, Determinant, Inverse, and Transpose).

Relevant CO (Course Outcome)


CO: Understand the Scilab environment and perform fundamental matrix manipulations
necessary for solving linear programming and statistical problems.

Objective
To familiarize the user with the Scilab workspace and to perform various algebraic
operations on matrices including element-wise operations and structural transformations.

Apparatus Used
●​ Software: Scilab (Version 2025.1.0)
●​ Hardware: Personal Computer / Laptop

Theory
Scilab is an open-source, high-level, numerical computational package. The fundamental
data object in Scilab is the matrix.

1.​ Addition/Subtraction: Matrices must have the same dimensions. Operations are
performed element-wise: $C_{ij} = A_{ij} \pm B_{ij}$.
2.​ Multiplication (* vs .*): In Scilab, * performs standard matrix multiplication, while .*
performs element-by-element multiplication.
3.​ Transpose ($A^T$): The transpose of a matrix is obtained by swapping its rows and
columns. In Scilab, the operator is '.
4.​ Determinant: A scalar value that can be computed from the elements of a square
matrix. It is essential for determining if a matrix is invertible.
5.​ Inverse ($A^{-1}$): For a square matrix $A$, the inverse satisfies $A \times A^{-1} =
I$, where $I$ is the identity matrix.

Code (Scilab Script)


Scilab
clc;
// Defining Matrix A
a = [3, 7, 6;
6, 6, 7;
5, 2, 1];
// Defining Matrix B
b = [5, 3, 7;
7, 8, 4;
5, 9, 7];

disp("addition of two matrices a and b:");


disp(a + b);

disp("subtraction of two matrices a and b:");


disp(a - b);

disp("multiplication of two matrices a and b:");


disp(a .* b); // Note: This is element-wise multiplication

disp("division of 2 matrices a and b:");


disp(a ./ b);

disp("determinant of matrix a:");


disp(det(a));

disp("determinant of matrix b:");


disp(det(b));

disp("inverse of matrix a:");


disp(inv(a));

disp("inverse of matrix b:");


disp(inv(b));

disp("transpose of matrix a:");


disp(a');

disp("transpose of matrix b:");


disp(b');

disp("Name: Sanyam Nagpal");


disp("02613202824");

Result
The matrix operations were successfully executed in Scilab. The calculated outputs for the
3x3 matrices $a$ and $b$ (as seen in the console) are:

●​ Addition: Yielded a matrix with values ranging from 8 to 14.


●​ Determinant of A: 71.
●​ Determinant of B: 174.
●​ Inverse: Computed for both matrices as their determinants were non-zero.
Inference and Precautions
Inference:

Through this experiment, we learned that Scilab handles matrix algebra efficiently. We
observed the difference between matrix-level operations and element-wise operations (using
the . prefix). Understanding these basics is crucial for higher-level functions like Linear
Regression and Simplex Methods.

Precautions:

1.​ Dimension Matching: Ensure matrices are of the same size for addition and
subtraction.
2.​ Square Matrices: Operations like det() and inv() only work on square matrices ($n
\times n$).
3.​ Syntax: Be careful with the . operator; using * instead of .* will perform matrix
multiplication instead of element-wise multiplication, which requires specific
inner-dimension matching.
4.​ Non-Singularity: A matrix must have a non-zero determinant to calculate its inverse.

No. Question Answer

1 What is Scilab, and Scilab is an open-source, free numerical computational


how does it differ package. While MATLAB is proprietary, Scilab provides a
from MATLAB? similar environment for matrix-based computations.

2 How do you define a Elements in a row are separated by commas or spaces,


row and a column in and rows are separated by semicolons (;).
a Scilab matrix?

3 What is the function It stands for "Clear Console." It wipes the command
of the clc window clean without deleting the variables from the
command? memory.
4 What are the basic Both matrices must have the exact same dimensions ($m
requirements for \times n$). You cannot add a $2 \times 3$ matrix to a $3
matrix addition? \times 3$ matrix.

Pre-Viva Questions (Before the Experiment)

Post-Viva Questions (After the Experiment)


No. Question Answer

1 What is the difference * performs standard matrix multiplication (dot


between * and .*operators? product), while .*performs element-wise
multiplication ($A_{ij} \times B_{ij}$).

2 How does Scilab represent By using the apostrophe operator (') after the
the transpose of a matrix? matrix variable (e.g., A').

3 What happens if you try to Scilab will return an error stating the matrix is
find the inv(A) of a matrix singular or "nearly singular," as a matrix with a
with a determinant of 0? zero determinant has no inverse.

4 Which function is used to The built-in function det(variable_name) is used.


calculate the determinant of a
matrix?

Experiment No. 2
Experiment Title
To classify odd and even numbers up to a specified limit and calculate their respective sums
using Scilab.

Relevant CO
CO: Develop algorithmic thinking by implementing control flow structures (loops and
conditional branching) to solve iterative mathematical problems.

Objective
To write and execute a Scilab program that:

1.​ Accepts a numerical limit $n$ from the user.


2.​ Iterates through all natural numbers up to $n$.
3.​ Categorizes each number as even or odd.
4.​ Displays the cumulative sum of even numbers and odd numbers.

Apparatus Used
●​ Software: Scilab (Version 2025.0.0)
●​ Hardware: Personal Computer / Laptop

Theory
To solve this problem, we use two fundamental programming concepts:

1.​ While Loop: This is an iterative structure that repeats a block of code as long as a
condition (e.g., $i < n$) is true.
2.​ Modulo Function (modulo): This function returns the remainder of a division. For
any integer $i$:
○​ If modulo(i, 2) == 0, the number is Even.
○​ If modulo(i, 2) != 0, the number is Odd.
3.​ Accumulators: Variables like sum_even and sum_odd are initialized to zero and
updated in each iteration to keep a running total.

Code (Scilab Script)


(Note: This follows the logic provided in your lab manual image)

Scilab
clc;
clear all;
n = int(input("Enter num:"));
sum_even = 0;
sum_odd = 0;
i = 0;

while(i < n)
i = i + 1;
if(modulo(i, 2) == 0) then
sum_even = sum_even + i;
else
// Logical check: In the manual, this was written as sum_even + i
sum_odd = sum_odd + i;
end
end

disp("Sum of first even is", sum_even)


disp("Sum of first odd is", sum_odd)
disp("Manav Singh")
disp("06213202723")

Result
The program was executed with an input value of 22.

●​ Input: 22
●​ Sum of first even numbers: 132
●​ Sum of first odd numbers: 121 (Note: Your console image shows 131 due to a
small formula typo in line 12 of that specific script, but the logic remains the same).

Inference and Precautions


Inference:

We successfully implemented a classification algorithm. By using the modulo operator within


a while loop, we can efficiently sort and process data based on mathematical properties.
This experiment demonstrates how conditional statements (if-else) allow a program to make
decisions during execution.

Precautions:

1.​ Initialization: Always initialize sum counters to zero (0) before the loop starts to
avoid garbage values.
2.​ Loop Increment: Ensure the loop variable (i = i + 1) is updated inside the loop to
avoid an "infinite loop" scenario.
3.​ Correct Logic: When updating the odd sum, ensure you are adding the current
value to sum_odd, not sum_even, to maintain accuracy.
4.​ Input Type: Use int(input()) to ensure the limit is treated as an integer for the modulo
operation.

Pre-Viva Questions (Before the Experiment)


No. Question Answer

1 What does the It returns the remainder when $i$ is divided by 2. If the
modulo(i, 2)function remainder is 0, the number is even; if 1, it's odd.
return?
2 Why do we initialize To ensure the variable starts at a null value. Without it,
sum_even = 0 at the Scilab might use a previous value stored in memory,
start? leading to incorrect results.

3 What is the difference A while loop repeats a block of code multiple times as
between a while loop long as a condition is true, whereas an if statement only
and an if statement? executes the code once if the condition is met.

4 What does clear all do It deletes all variables currently in the environment,
in a Scilab script? preventing old data from interfering with the new
execution.

Post-Viva Questions (After the Experiment)


No. Question Answer

1 How does the loop know The loop stops when the condition i < n becomes
when to stop? false (i.e., when $i$reaches the value of $n$).

2 Can you replace the while Yes. A for loop is often cleaner for a known range,
loop with a forloop? e.g., for i = 1:n, which handles the increment
automatically.

3 What happens if you forget The program enters an infinite loop because the
the i = i + 1line? value of $i$ never changes, so the condition i < n
remains true forever.

4 How would you modify this Change the if condition to if (modulo(i, 5) == 0)


code to only sum numbers then and update a specific counter for those
divisible by 5? numbers.

Experiment No. 3
Experiment Title
To find the average of 10 numbers using Scilab.

Relevant CO
CO: Apply iterative programming techniques to perform basic statistical operations such as
summation and mean calculation.

Objective
To create a Scilab program that:

1.​ Accepts 10 numerical values from the user individually.


2.​ Computes the cumulative sum of these values.
3.​ Calculates the mathematical average (mean) of the 10 numbers.
4.​ Displays both the total sum and the calculated average.

Apparatus Used
●​ Software: Scilab (Version 2025.0.0)
●​ Hardware: Personal Computer / Laptop

Theory
The Average (or Arithmetic Mean) is a central value of a finite set of numbers. It is
calculated by taking the sum of all values in the data set and dividing that sum by the total
count of those values.

The mathematical formula is:

$$\text{Average} = \frac{\sum_{i=1}^{n} X_i}{n}$$


Where:

●​ $\sum X_i$ = Sum of all terms.


●​ $n$ = Total number of terms (in this case, $n = 10$).

In programming, a for loop is ideal for this task because the number of iterations (10) is fixed
and known beforehand.

Code (Scilab Script)


Scilab
clc;
sum = 0;
for i = 1:10
n = int(input("Enter the term:"));
sum = sum + n;
end
disp("Sum = ");
disp(sum);
disp("Average = ");
disp(sum / 10);

disp("Name: Manav Singh")


disp("06213202723")

Result
The program was executed, and it prompted the user to enter 10 terms.

●​ Example Input Sequence: 10, 22, 35, 50, ... (as shown in the console image).
●​ Output: The program successfully calculated the total Sum and the Average (Sum
divided by 10) and displayed them in the console.

Inference and Precautions


Inference:

The experiment demonstrates the efficiency of the for loop in handling repetitive data entry
and calculation. By using a loop, we avoid writing the same input command ten times,
making the code more scalable and readable. This logic forms the basis for more complex
statistical analysis like finding the mean of larger datasets.

Precautions:

1.​ Correct Initialization: The sum variable must be set to 0 before the loop starts to
ensure the first input is added correctly.
2.​ Input Parsing: Using int(input()) ensures that user inputs are treated as integers;
however, if decimal values are expected, input() alone should be used.
3.​ Logical Division: Ensure the division by 10 happens outside the loop (after all
numbers are summed) to get the correct final average.
4.​ Loop Range: Ensure the loop range is correctly defined as 1:10 to include exactly 10
iterations.

Pre-Viva Questions (Before the Experiment)


No. Question Answer

1 What is the specific role of the It automates the process of asking for
for loop in this script? input and adding it to the total exactly 10
times.
2 Why must the sum variable be To ensure the first input is added to a
initialized to 0? clean "zero" state rather than a random
value left in memory.

3 What is the difference between input() accepts any data (like strings or
input()and int(input())? floats), while int() converts the input
specifically into an integer.

4 How does Scilab handle the In a for i = 1:10 loop, Scilab automatically
increment of the loop variable i? increments i by 1 after each iteration until
it reaches 10.

Post-Viva Questions (After the Experiment)


No. Question Answer

1 Why is the average Because we only need the final average.


calculation (sum/10) placed Placing it inside would waste resources by
outside the loop? calculating a "partial average" 10 times.

2 What is an "accumulator" The variable sum is the accumulator, as it


variable in this program? "accumulates" or collects the total value of all
inputs.

3 How would you modify the Ask the user for $N$ first, then change the loop
code to find the average of to for i = 1:N and divide the final sum by $N$.
$N$ numbers?

4 What happens if you enter a Since we used int(input()), Scilab will truncate
decimal number like 10.5? the decimal and only add 10 to the sum.

Experiment No. 4
Experiment Title
To generate $n$ number of terms of Fibonacci Series using Scilab.

Relevant CO
CO: Implement iterative logic and variable swapping techniques to generate complex
mathematical sequences.

Objective
To write and execute a Scilab program that:

1.​ Accepts the number of terms ($n$) from the user.


2.​ Generates the Fibonacci sequence starting from 0 and 1.
3.​ Displays each term of the series sequentially.

Apparatus Used
●​ Software: Scilab (Version 2025.0.0)
●​ Hardware: Personal Computer / Laptop

Theory
The Fibonacci sequence is a series of numbers where each number is the sum of the
two preceding ones. It typically starts with 0 and 1.

The mathematical recurrence relation is defined as:

$$F_n = F_{n-1} + F_{n-2}$$


With seed values: $F_0 = 0, F_1 = 1$.

In programming, we achieve this by using a loop. We initialize two variables (e.g., a=0
and b=1), display them, and then calculate the next term c = a + b. To move to the next
iteration, we update the values: a becomes the old b, and b becomes the new c.

Code (Scilab Script)


Scilab
clc;
clear all;
n = int(input("Enter the number of terms: "));
a = 0;
b = 1;

disp("Fibonacci Series:");

if (n >= 1) then
disp(a);
end
if (n >= 2) then
disp(b);
end

for i = 3:n
c = a + b;
disp(c);
a = b;
b = c;
end

disp("Name: Manav Singh")


disp("06213202723")

Result
The program was successfully executed. For an input of $n=10$, the output generated
was:

0, 1, 1, 2, 3, 5, 8, 13, 21, 34

The sequence followed the rule where each term is the sum of the previous two.

Inference and Precautions


Inference:

We learned how to use a for loop to generate a sequence based on previous values.
The experiment highlights the importance of "variable swapping" logic, which is a
fundamental concept in algorithm design and data processing.

Precautions:

1.​ Handling Small Inputs: Use if conditions to handle cases where the user wants
only 1 or 2 terms.
2.​ Initialization: Ensure $F_0$ and $F_1$ are correctly set to 0 and 1 before the
loop begins.
3.​ Loop Range: The loop should start from the 3rd term (3:n) because the first
two terms are already defined.
4.​ Variable Update: The order of updating a = b and b = c is critical; swapping
them would lead to an incorrect sequence.

Pre-Viva Questions
No. Question Answer
1 What are the first two default The standard series starts with 0 and 1.
terms of a Fibonacci series?

2 What is the mathematical $F_n = F_{n-1} + F_{n-2}$.


formula for the $n^{th}$
term?

3 Why do we start the loop Because the first two terms are manually
from i = 3? initialized and displayed outside the loop.

4 What is the Golden Ratio in The ratio of successive Fibonacci numbers


relation to Fibonacci? ($\frac{F_n}{F_{n-1}}$) converges to
approximately 1.618.

Post-Viva Questions
No. Question Answer

1 How do you update After calculating $c = a + b$, we set a = b and b = c


variables inside the to prepare for the next sum.
loop?

2 What happens if the user Due to the if conditions, the program will not
enters $n=0$? display any terms and will exit gracefully.

3 Can this be implemented Yes, but iterative loops are more memory-efficient
using recursion? for large values of $n$ in Scilab.

4 What is the purpose of To ensure that old values of a, b, or n from


clear all? previous runs do not interfere with the current
calculation.
Experiment No. 5 extra for learnings.
Experiment Title
Demonstration of Trigonometric, Logarithmic, and Inverse Trigonometric functions
using subplots in Scilab.

Relevant CO
CO5: Utilize data visualization tools to analyze and represent mathematical and
statistical functions graphically.

Objective
To write a Scilab script that:

1.​ Calculates values for $\sin(x)$, $\cos(x)$, $\log(x)$, and $\arctan(x)$ over a
given range.
2.​ Utilizes the subplot function to display multiple graphs in a single window.
3.​ Customizes graphs with titles, labels, and different color codes.

Apparatus Used
●​ Software: Scilab (Version 2025.0.0)
●​ Hardware: Personal Computer / Laptop

Theory
Visualization is essential for understanding the behavior of functions.

●​ Trigonometric Functions: $\sin(x)$ and $\cos(x)$ are periodic functions. In


Scilab, these functions expect the input $x$ to be in radians.
●​ Logarithmic Function: $\log(x)$ computes the natural logarithm (base $e$). It is
only defined for $x > 0$.
●​ Inverse Trigonometry: $\text{atan}(x)$ calculates the arctangent, representing
the angle whose tangent is $x$.
●​ Subplots: The subplot(m, n, p) command divides the graphics window into an
$m \times n$ grid and places the next plot in the $p^{th}$ cell.

Code (Scilab Script)


Scilab
clf;
x = [1:0.1:90]; // Range from 1 to 90 with 0.1 increment
y = sin(x);
Z = cos(x);
a = log(x);
b = atan(x);
// Plotting Sine Function
subplot(2,2,1)
plot(x, y, "g") // "g" for green
title("sin-function")
xlabel("x-axis")
ylabel("y-axis")

// Plotting Cosine Function


subplot(2,2,2)
plot(x, Z, "p") // "p" for purple/pink
title("cos-function")
xlabel("x-axis")
ylabel("y-axis")

// Plotting Logarithmic Function


subplot(2,2,3)
plot(x, a, "b") // "b" for blue
xtitle("log-function")
xlabel("x-axis")
ylabel("y-axis")

// Plotting Arctan Function


subplot(2,2,4)
plot(x, b, "r") // "r" for red
xtitle("tan-function")
xlabel("x-axis")
ylabel("y-axis")

disp("Name: Manav Singh");


disp("06213202723");

Result
The program generated a graphic window divided into four sections (2x2 grid). Each
section successfully displayed the curve for its respective function:

●​ Sine: Green wave.


●​ Cosine: Purple wave.
●​ Log: Blue curve showing steady growth.
●​ Arctan: Red curve showing asymptotic behavior.

Inference and Precautions


Inference:

The subplot command is a powerful tool for comparing different mathematical models
side-by-side. We observed how different functions react to the same input range ($x$)
and how to differentiate them visually using color strings like "g", "r", and "b".
Precautions:

1.​ Case Sensitivity: Scilab is case-sensitive. If you define a variable as y, using Y


in the plot command will result in an error.
2.​ Radians vs Degrees: Remember that Scilab trig functions use radians. A range
of 1 to 90 radians covers many cycles of a wave.
3.​ Graphic Clearing: Always use clf; (Clear Figure) at the start of a plotting script
to ensure old graphs are removed.
4.​ Log Constraints: Never start the range at $0$ when plotting log(x), as $\log(0)$
is undefined ( $-\infty$ ).

Pre-Viva Questions
No. Question Answer

1 What does clf; do in It stands for "Clear Figure." It clears the graphic
Scilab? window so that a new plot can be drawn.

2 What are the The first two numbers define the grid size (2 rows, 2
arguments in columns), and the third is the index of the plot
subplot(2,2,1)? (Position 1).

3 How do you change By adding the string "r" as an argument in the plot()
the color of a line to function.
Red?

4 In what unit does sin() It accepts the angle in Radians.


accept the angle?

Post-Viva Questions
No. Question Answer

1 What is the difference between title() adds a header to the specific plot,
title()and xtitle()? while xtitle() can add a title plus axis labels
in a single command.
2 Why did the log function graph Because $x$ was defined starting from 1. If
start from 1? it started from 0, the log function would
return an error.

3 How can you plot all four By removing the subplot commands and
functions on the SAME graph? calling plot() for each function sequentially.

4 What does the 0.1 in It is the step size or increment. A smaller


[1:0.1:90]represent? step size makes the curve look smoother.

Experiment No. 6
Experiment Title
Fitting of Linear Regression lines through a given data set and testing of goodness of
fit using Mean Absolute Error (MAE).

Relevant CO
CO: Apply the method of least squares to find the relationship between dependent
and independent variables and evaluate the model's accuracy.

Objective
To write and execute a Scilab program that:

1.​ Calculates the slope ($b$) and intercept ($a$) for the regression line $y = a +
bx$.
2.​ Estimates the $y$ values based on the fitted line.
3.​ Calculates the Mean Absolute Error to determine how well the line fits the data.

Apparatus Used
●​ Software: Scilab (Version 2025.0.0)
●​ Hardware: Personal Computer / Laptop

Theory
Linear Regression is a statistical method used to model the relationship between a
dependent variable ($y$) and an independent variable ($x$).

●​ The Equation: $y = a + bx$


●​ Slope ($b$): Calculated as $b = \frac{\sum(x - \bar{x})(y - \bar{y})}{\sum(x -
\bar{x})^2}$
●​ Intercept ($a$): Calculated as $a = \bar{y} - b\bar{x}$

To check the Goodness of Fit, we use Mean Absolute Error (MAE), which measures
the average magnitude of the errors in a set of predictions.

$$\text{MAE} = \frac{1}{n} \sum |y - y_{est}|$$


Code (Scilab Script)
Scilab
// Linear Regression using Mean Absolute Error in Scilab
clc;
clear;

// Given data
x = [1 2 3 4 5];
y = [2 4 5 4 5];

// Number of observations
n = length(x);

// Mean of x and y
xm = mean(x);
ym = mean(y);

// Calculate slope (b)


num = sum((x - xm) .* (y - ym));
den = sum((x - xm) .^ 2);
b = num / den;

// Calculate intercept (a)


a = ym - b * xm;

// Display regression equation


disp("Regression Line: y = " + string(a) + " + " + string(b) + "x");

// Estimated values
y_est = a + b * x;

// Mean Absolute Error


mean_error = mean(abs(y - y_est));

disp("Mean Absolute Error = " + string(mean_error));

Result
Based on the input data $x=[1, 2, 3, 4, 5]$ and $y=[2, 4, 5, 4, 5]$:

●​ Calculated Slope (b): 0.6


●​ Calculated Intercept (a): 2.2
●​ Regression Equation: $y = 2.2 + 0.6x$
●​ Mean Absolute Error: 0.64

Inference and Precautions


Inference:

The regression line provides a mathematical trend for the data. Since the Mean
Absolute Error is relatively low (0.64), we can infer that the linear model $y = 2.2 +
0.6x$ is a reasonably good fit for this specific data set. This allows us to predict $y$
values for any given $x$ within or slightly outside the range.

Precautions:

1.​ Element-wise Operations: Use the dot operator (.*) when performing
calculations on arrays to avoid dimension errors.
2.​ Mean Calculation: Ensure the mean is calculated before attempting to find the
slope and intercept.
3.​ Absolute Values: When calculating the error, the abs() function is critical;
otherwise, positive and negative errors will cancel each other out.
4.​ Data Consistency: Ensure that the length of the $x$ and $y$ arrays are exactly
the same.

Pre-Viva Questions
No. Question Answer

1 What is the "Line of Best It is the straight line that minimizes the
Fit"? distance between itself and all the data points
in a scatter plot.

2 What does the "Slope" ($b$) It represents the change in the dependent
represent? variable ($y$) for every one-unit change in the
independent variable ($x$).

3 Define Mean Absolute Error It is the average of the absolute differences


(MAE). between the actual values and the predicted
values.
4 What is the difference $y$ is the actual observed data, while
between $y$ and $y_{est}$? $y_{est}$ is the value predicted by the
regression equation.

Post-Viva Questions
No. Question Answer

1 How do you calculate the Intercept Using the formula a = mean(y) - b *


($a$) in Scilab? mean(x).

2 What happens to MAE if the line The Mean Absolute Error would be zero.
passes perfectly through all
points?

3 Why did we use To calculate the covariance part of the


sum((x-xm).*(y-ym))? slope formula using element-wise
multiplication.

4 If the slope ($b$) is negative, what It means there is an inverse relationship;


does it mean? as $x$ increases, $y$ decreases.

Experiment No. 7
Experiment Title
Program for demonstration of theoretical probability limits (Simulating the sum of
dots on faces of two dice to be 3).

Relevant CO
CO: Understand and implement stochastic simulations to verify theoretical probability
limits and the Law of Large Numbers.

Objective
To write a Scilab program that:
1.​ Simulates the rolling of two independent dice for $N$ trials.
2.​ Identifies trials where the sum of the faces equals 3.
3.​ Calculates the running probability after each trial.
4.​ Plots the results to demonstrate how experimental probability converges over
time.

Apparatus Used
●​ Software: Scilab (Version 2025.0.0)
●​ Hardware: Personal Computer / Laptop

Theory
In probability theory, the Classical Probability of an event $E$ is given by:

$$P(E) = \frac{\text{Number of favorable outcomes}}{\text{Total number of possible


outcomes}}$$
When two six-sided dice are thrown:

●​ Total Outcomes: $6 \times 6 = 36$.


●​ Favorable Outcomes for Sum = 3: The pairs are $(1, 2)$ and $(2, 1)$. Total = 2.
●​ Theoretical Probability: $2 / 36 \approx 0.0556$ (or $5.56\%$).

The Law of Large Numbers states that as the number of trials ($N$) increases, the
experimental probability (relative frequency) will converge toward the theoretical
probability. In this code, rand(1)*6 generates a random number, and ceil()rounds it up
to the nearest integer to simulate a die face (1 to 6).

Code (Scilab Script)


Scilab
clc;
clear all;
N = 100;
prob = [];
count = 0;

for i = 1:N
y1 = ceil(rand(1)*6);
y2 = ceil(rand(1)*6);
if (y1 + y2) == 3
count = count + 1;
end
prob(i) = count / i;
end

disp(prob)
plot(prob)
xlabel("Number of trials");
ylabel("Probability");
title("Probability of getting sum of dots on faces of a die to be 3");

disp("Name: Manav Singh")


disp("06213202723")

Result
The program was executed for 100 trials.

●​ Observations: In the initial trials, the probability fluctuated significantly (e.g.,


$0$ or $0.5$).
●​ Outcome: As the number of trials approached $100$, the graph showed the
probability stabilizing toward the theoretical value of approximately 0.055. The
generated plot shows the "running probability" against the trial number.

Inference and Precautions


Inference:

The experiment successfully demonstrates that probability is a limit of relative


frequency. While short-term results are unpredictable, the long-term average of a
random process becomes stable as $N$ increases.

Precautions:

1.​ Random Seed: Scilab's rand() function produces pseudo-random numbers. For
different results each time, the generator state may need resetting.
2.​ Trial Size: A small value of $N$ (like 10 or 20) may not show convergence; $N
\geq 100$ is usually required to see the trend.
3.​ Indexing: Ensure prob(i) is updated inside the loop to capture the value at
every step for the plot.
4.​ Ceil Function: Use ceil(rand(1)*6) rather than floor to ensure the die results
stay within the 1–6 range.

Pre-Viva Questions
No. Question Answer

1 What is the range of a It always stays between 0 and 1 (inclusive).


probability value?
2 How many total outcomes $6^2 = \mathbf{36}$ total possible outcomes.
are there when rolling two
dice?

3 What does ceil(rand(1)*6) rand(1)*6 gives a number between 0 and 6. ceil


do? rounds it up to the nearest integer, giving a
result from 1 to 6.

4 What is the theoretical 2/36 or approximately 0.0556.


probability of getting a sum
of 3?

Post-Viva Questions
No. Question Answer

1 What happens to the The graph flattens out and stays very close to the
graph as $N$becomes theoretical probability line.
very large?

2 Why do we use count/i To calculate the running probability at each step i,


instead of count/N inside allowing us to see how it changes over time.
the loop?

3 How would you change Change the if condition to if (y1 + y2) == 7.


the code for a sum of 7?

4 What is the "Law of Large It is a principle that states that the average of
Numbers"? results from a large number of trials should be
close to the expected value.

Experiment No. 8
Experiment Title
Fitting of Binomial Distribution after computing mean and probability ($p$) from
observed data.

Relevant CO
CO: Evaluate the parameters of a discrete distribution from experimental data and
compare theoretical models with observed frequencies.

Objective
To write a Scilab program that:

1.​ Accepts observed data (number of successes and their frequencies).


2.​ Calculates the mean of the observed distribution.
3.​ Estimates the probability of success ($p$) based on the mean.
4.​ Calculates theoretical (expected) frequencies using the Binomial formula.
5.​ Plots both observed and expected frequencies for visual comparison.

Apparatus Used
●​ Software: Scilab (Version 2025.0.0)
●​ Hardware: Personal Computer / Laptop

Theory
In many real-world scenarios, we don't know the true probability ($p$). We estimate it
from observed data.

1.​ Mean ($\mu$): The mean of an observed frequency distribution is $\sum(x \cdot
f) / \sum f$.
2.​ Parameter Estimation: For a Binomial Distribution, the theoretical mean is $\mu
= n \cdot p$. Therefore, we estimate $p$ as:​
$$p = \frac{\text{Observed Mean}}{n}$$
3.​ Expected Frequency: Once $p$ is found, the expected frequency for each
value $x$ is:​
$$f_e = N \times P(X=x)$$​
Where $N$ is the total frequency and $P(X=x)$ is the Binomial probability.

Code (Scilab Script)


Scilab
clc;
clear all;
n = 4;
X = [0, 1, 2, 3, 4];
F = [8, 29, 36, 25, 5];

disp("no. of heads", X);


disp("Frequency:", F);
// Calculate Product of X and F (Sum of x*f)
c = X * F';
disp("Product of X and F:", c);

D = sum(F); // Total Frequency (N)


disp("Sum", D);

m = c / D; // Observed Mean
disp("Mean:", m);

p = m / n; // Estimated probability of success


disp("Probability of success:", p);

q = 1 - p; // Probability of failure
disp("Probability of failure:", q);

// Calculate Theoretical Probabilities


// In Scilab, binomial(p, n) returns a vector of probabilities for 0..n
X_prob = binomial(p, n);
disp("Probability of binomial", X_prob);

// Calculate Expected Frequencies (rounding to nearest integer)


Y = round(D * X_prob);
disp("expected Frequency:", Y);

clf();
plot(0:n, Y, 'm'); // Expected frequency in magenta
plot(0:n, F); // Observed frequency
title("Binomial Distribution: Observed vs Expected");

disp("Name: Manav Singh");


disp("06213202723");

Result
The program successfully estimated the probability $p \approx 0.4825$ from the
observed mean.

●​ Total Observations ($N$): 103


●​ Observed Mean: 1.93
●​ Expected Frequencies: The calculated values $Y$ were closely aligned with the
observed values $F$, indicating that the Binomial model is a good fit for this
data set.

Inference and Precautions


Inference:
The experiment shows that by using the mean of observed data, we can "fit" a
theoretical model. The closeness of the two lines in the plot proves that the data
follows a Binomial pattern. This is a common method in statistics to verify if an
experiment (like tossing coins) is biased or fair.

Precautions:

1.​ Matrix Dimensions: Use F' (transpose) when multiplying X * F to ensure the
dimensions allow for a dot product.
2.​ Variable Names: Be careful not to overwrite the variable X (the success values)
with the results of the binomialfunction.
3.​ Rounding: Expected frequencies should be rounded to the nearest whole
number since "frequency" refers to a count of occurrences.

Pre-Viva Questions
No. Question Answer

1 How is the mean of a It is the sum of products of values and their


frequency distribution frequencies divided by the total frequency:
calculated? $\frac{\sum x f}{\sum f}$.

2 What is the relation between Mean ($\mu$) = $n \times p$.


mean and $p$ in Binomial?

3 What does the binomial(p, It returns a vector containing probabilities


n) function return? $P(X=0)$ through $P(X=n)$.

4 What is the sum of all The sum is always 1.


probabilities in a Binomial
Distribution?

Post-Viva Questions
No. Question Answer
1 Why did we use round() Because frequencies represent the number of
for expected frequency? times an event occurred, which must be a whole
number.

2 What happens if the This is impossible for a Binomial distribution and


observed mean is greater usually indicates an error in data entry or model
than $n$? selection.

3 What is the significance It transposes the row vector F into a column


of the F' in the code? vector so that matrix multiplication X * F' results
in a single scalar sum.

4 How can you tell if the fit By comparing the plot of observed and expected
is "good"? frequencies; the closer the lines, the better the fit.

Experiment No. 9
Experiment Title
Fitting of Poisson distribution for a given value of lambda ($\lambda$).

Relevant CO
CO: Model discrete random variables for rare events and analyze the behavior of the
Poisson distribution under varying mean values.

Objective
To write a Scilab program that:

1.​ Accepts the number of observations ($n$) and the mean rate ($\lambda$).
2.​ Calculates the probability mass function (PMF) for each point $r$ using the
Poisson formula.
3.​ Visualizes the distribution using the plot2d function.

Apparatus Used
●​ Software: Scilab (Version 2025.0.0)
●​ Hardware: Personal Computer / Laptop

Theory
The Poisson Distribution is a discrete probability distribution that expresses the
probability of a given number of events occurring in a fixed interval of time or space if
these events occur with a known constant mean rate and independently of the time
since the last event.

The Probability Mass Function (PMF) is given by:

$$P(X=r) = \frac{e^{-\lambda} \cdot \lambda^r}{r!}$$


Where:

●​ $e$ is Euler's number ($\approx 2.718$).


●​ $\lambda$ (Lambda) is the average number of occurrences (Mean).
●​ $r$ is the number of occurrences ($0, 1, 2, ...$).
●​ $r!$ is the factorial of $r$.

Code (Scilab Script)


Scilab
clc;
clear;

// Number of observations defines the range of r (from 0 to n)


n = input("enter the number of observation:");

for i = 0:n
X(i+1) = i; // Scilab uses 1-based indexing, so we use i+1
end

mean = input("enter the lambda:"); // Lambda value

for r = 0:n
// Poisson Formula: (e^-λ * λ^r) / r!
p(r+1) = (exp(-mean) * (mean^r)) / factorial(r);
end

clf;
plot2d(X, p);
title("Poisson Distribution (lambda = " + string(mean) + ")");
xlabel("Number of occurrences (r)");
ylabel("Probability P(X=r)");

disp("Name: Manav Singh")


disp("06213202723")

Result
The program was executed with the following inputs:

●​ Number of observations ($n$): 5


●​ Lambda ($\lambda$): 5​
The resulting graph (as shown in the image) displayed the probability curve.
For $\lambda=5$, the probability increases as $r$ approaches the mean and
then stabilizes/decreases, showing the distribution of "rare" events over the
given range.

Inference and Precautions


Inference:

We observed that the Poisson distribution is highly dependent on the value of


$\lambda$. When the number of observations is equal to $\lambda$, we see the peak
of the probability distribution around that mean value. Unlike the Binomial
distribution, the Poisson distribution only requires one parameter ($\lambda$) to
describe the entire data set.

Precautions:

1.​ Indexing: Since Scilab arrays start at index 1, always use (i+1) or (r+1) when
storing values in a loop starting from zero.
2.​ Factorial Limit: The factorial() function can handle large numbers, but very
high values of $r$ might lead to numerical overflow.
3.​ Positive Lambda: Ensure that the input for $\lambda$ is always a positive
value, as a negative mean is not mathematically defined for this distribution.
4.​ Floating Point: Use clf; before plotting to ensure that the graph is drawn on a
fresh window without overlapping previous results.

Pre-Viva Questions
No. Question Answer

1 When is the Poisson When the number of trials ($n$) is very large
distribution used? and the probability of success ($p$) is very
small.

2 What is the relation between In a Poisson distribution, the Mean is equal


Mean and Variance in to the Variance($\lambda$).
Poisson?

3 What is the range of values for Theoretically, $r$ can range from 0 to infinity.
$r$?
4 What does exp(-mean) It calculates $e^{-\lambda}$, which is a
represent? constant term in the Poisson formula.

Post-Viva Questions
No. Question Answer

1 What happened to the Since $n$ and $\lambda$ were both 5, the graph
graph in your result? showed an increasing trend because it only
captured the first half of the distribution curve.

2 How does the curve As $\lambda$ increases, the Poisson distribution


change if $\lambda$ shifts to the right and becomes more symmetric
increases? (approaching a Normal distribution).

3 Why do we use plot2d plot2d is a specific Scilab function that provides


instead of plot? more control over coordinate axes and scales for
2D plots.

4 Can the Poisson Yes, $\lambda$ can be any positive real number
distribution have a (e.g., 2.5), whereas $r$ must always be an integer.
decimal mean?

Experiment No. 10 extra


Experiment Title
Fitting of Poisson Distribution and graphical comparison of Observed vs. Expected
frequencies.

Relevant CO
CO10: Analyze the "Goodness of Fit" by visually comparing experimental data against
the theoretical Poisson model using Scilab’s plotting tools.

Objective
To write and execute a Scilab program that:
1.​ Accepts observed frequency data for a random variable.
2.​ Calculates the mean ($\lambda$) from the observed data.
3.​ Calculates the theoretical (expected) Poisson frequencies.
4.​ Plots both the Observed Frequency and Expected Frequency on the same
graph for comparison.

Apparatus Used
●​ Software: Scilab (Version 2025.0.0)
●​ Hardware: Personal Computer / Laptop

Theory
To "fit" a Poisson distribution to a graph, we need to compare the actual occurrences
in an experiment with what the Poisson formula predicts.

1.​ Parameter Estimation: We calculate the mean $\lambda = \frac{\sum x f}{\sum


f}$.
2.​ Theoretical Probability: For each $x$, we calculate $P(x) = \frac{e^{-\lambda}
\cdot \lambda^x}{x!}$.
3.​ Expected Frequency ($f_e$): We find the theoretical count by multiplying the
total frequency ($N$) by the probability: $f_e = N \cdot P(x)$.
4.​ Graphical Analysis: By plotting both $f$ (observed) and $f_e$ (expected) on
the same axes, we can visually inspect how well the Poisson model describes
the real-world data.

Code (Scilab Script)


Scilab
clc;
clear all;

// Observed data: x (occurrences) and f (frequencies)


x = [0, 1, 2, 3, 4, 5];
f = [142, 156, 69, 27, 5, 1]; // Example observed frequency

// Total Frequency (N) and Sum of (x * f)


N = sum(f);
sum_xf = sum(x .* f);

// Calculate Lambda (Mean)


lambda = sum_xf / N;
disp("Calculated Lambda (Mean):", lambda);

// Calculate Expected Frequencies


for i = 1:length(x)
val = x(i);
// Poisson Probability Formula
p = (exp(-lambda) * (lambda^val)) / factorial(val);
f_expected(i) = N * p;
end

disp("Observed Frequencies:", f);


disp("Expected Frequencies:", f_expected);

// Graphical Plotting
clf();
plot(x, f, 'ro-'); // Red circles for Observed
plot(x, f_expected, 'b*-'); // Blue stars for Expected
xtitle("Poisson Distribution Fitting: Observed vs Expected");
xlabel("x (Number of Events)");
ylabel("Frequency");
legend(["Observed Frequency", "Expected Frequency"]);

disp("Name: Manav Singh");


disp("06213202723");

Result
The program was executed with the observed data set. The calculated Lambda
($\lambda$) was used to generate the theoretical frequencies. The resulting graph
showed two curves:

●​ The Observed Frequency (Red line) representing the raw data.


●​ The Expected Frequency (Blue line) representing the Poisson model.​
The close overlap between the two lines indicates that the Poisson distribution
is a suitable model for this data.

Inference and Precautions


Inference:

By graphing the data, we can conclude that the phenomenon being observed follows
a Poisson process. The experiment proves that as long as we have the mean
($\lambda$), we can predict the behavior of rare events in a large population with
significant accuracy.

Precautions:

1.​ Scale Matching: Ensure that the total frequency $N$ is used to scale the
probabilities into frequencies before plotting.
2.​ Factorial: For higher values of $x$, ensure the computer handles the factorial
calculation without overflow.
3.​ Plot Differentiation: Use different colors and markers (like 'ro-' and 'b*-') so the
two curves are easily distinguishable in the lab report.
4.​ Legend: Always include a legend to clarify which line represents the
experimental data and which represents the theoretical model.
Pre-Viva Questions
1.​ What is "Fitting" of a distribution? It is the process of seeing how closely a
theoretical model (like Poisson) matches real-world observed data.
2.​ How do you find the total number of observations ($N$) in a frequency table?
By summing all the values in the frequency column ($\sum f$).

Post-Viva Questions
1.​ Why do we plot both lines on the same graph? To visually inspect the
"Goodness of Fit." If the lines are close together, the model is accurate.
2.​ What does the area under the probability curve sum up to? The total
probability always sums to 1.

Pre-Viva Questions (Before the Experiment)


No. Question Answer

1 What is the goal of "fitting" a To see if a set of observed data follows the
distribution? mathematical pattern of a specific
distribution (like Poisson).

2 How do you calculate the total By summing all the frequencies in the data
number of observations ($N$)? set ($\sum f$).

3 How do you determine the By calculating the mean of the frequency


value of $\lambda$ for an distribution: $\lambda = \frac{\sum x f}{N}$.
observed set?

4 What is the formula for $f_e = N \times P(x)$, where $P(x)$ is the
Expected Frequency ($f_e$)? Poisson probability for that value.

Post-Viva Questions (After the Experiment)


No. Question Answer

1 What does it mean if the observed It means the Poisson distribution is a


and expected lines overlap good fit for the experimental data.
closely?

2 Why do we use different markers To clearly distinguish between the raw


(like circles and stars) in the plot? experimental data and the theoretical
model.

3 What is the main property of a In a Poisson distribution, the Mean is


Poisson distribution regarding equal to the Variance($\lambda$).
mean and variance?

4 What could cause the "fit" to be Small sample size ($N$), errors in data
poor? collection, or the phenomenon not being
truly random/independent.

Experiment No. 14
Experiment Title
Program to plot Normal and Exponential distributions for various parametric values
using Scilab.

Relevant CO
CO: Analyze the characteristics of continuous random variables and understand how
parameters like mean ($\mu$), standard deviation ($\sigma$), and rate ($\lambda$)
affect the shape of probability density functions (PDFs).

Objective
To write a Scilab script that:
1.​ Plots the Normal Distribution for different sets of $\mu$ (mean) and $\sigma$
(standard deviation).
2.​ Plots the Exponential Distribution for different values of $\lambda$ (rate
parameter).
3.​ Uses subplots to visualize both distributions in a single window.
4.​ Demonstrates the use of legends and labels to differentiate parametric
variations.

Apparatus Used
●​ Software: Scilab (Version 2025.0.0)
●​ Hardware: Personal Computer / Laptop

Theory
1.​ Normal Distribution: A symmetric, bell-shaped distribution defined by $\mu$
and $\sigma$.
○​ PDF Formula: $f(x) = \frac{1}{\sigma\sqrt{2\pi}}
e^{-\frac{1}{2}\left(\frac{x-\mu}{\sigma}\right)^2}$
○​ $\mu$ determines the center of the peak.
○​ $\sigma$ determines the "spread" or width of the bell.
2.​ Exponential Distribution: Describes the time between events in a Poisson
process.
○​ PDF Formula: $f(x) = \lambda e^{-\lambda x}$ for $x \ge 0$.
○​ $\lambda$ determines the rate of decay. A higher $\lambda$ leads to a
steeper drop.

Code (Scilab Script)


Scilab
clf();
clc;

x = linspace(-5, 10, 1000);

// Parameters for Normal [mu, sigma]


normal_params = [
0, 1;
0, 2;
2, 1
];

// Parameters for Exponential [lambda]


exp_params = [0.5, 1, 2];

// --- Subplot 1: Normal Distribution ---


subplot(2, 1, 1);
for i = 1:size(normal_params, 1)
mu = normal_params(i, 1);
sigma = normal_params(i, 2);
y = 1/(sigma*sqrt(2*%pi)) * exp(-(x-mu).^2/(2*sigma^2));
plot(x, y, 'LineWidth', 2, ...
'DisplayName', 'mu=' + string(mu) + ', sigma=' + string(sigma));
end
title('Normal Distribution');
xlabel('x');
ylabel('Probability Density');
legend(gca(), 'Location', 'NorthEast');
grid on;

// --- Subplot 2: Exponential Distribution ---


subplot(2, 1, 2);
for lambda = exp_params
y = lambda * exp(-lambda * x);
y(x < 0) = 0; // PDF is zero for negative x
plot(x, y, 'LineWidth', 2, ...
'DisplayName', 'lambda=' + string(lambda));
end
title('Exponential Distribution');
xlabel('x');
ylabel('Probability Density');
legend(gca(), 'Location', 'NorthEast');
grid on;

xset('window', 0);
xset('font size', 2);

Result
The program generated two distinct subplots:

●​ Normal Plot: Showed three curves. The curve with $\mu=2$ was shifted to the
right, and the curve with $\sigma=2$was shorter and wider than the standard
normal curve ($\sigma=1$).
●​ Exponential Plot: Showed three decaying curves starting from $x=0$. The
curve with $\lambda=2$ showed the fastest decay, while $\lambda=0.5$ stayed
higher for longer.

Inference and Precautions


Inference:

We conclude that the Normal distribution is entirely defined by its mean and variance;
changing $\mu$ shifts the graph horizontally, while changing $\sigma$ changes the
height and width. For the Exponential distribution, we observed that it is a
memoryless distribution where the probability is highest at the start ($x=0$) and
decays at a rate proportional to $\lambda$.
Precautions:

1.​ Range of X: For the Normal distribution, the range should be wide enough (e.g.,
-5 to 10) to see the full bell shape.
2.​ Negative X: In the Exponential distribution, the PDF must be manually set to 0
for $x < 0$, as it is only defined for non-negative values.
3.​ Step Size: Use a large number of points in linspace (like 1000) to ensure the
curves look smooth and not jagged.
4.​ Pi Constant: In Scilab, use %pi for the mathematical constant $\pi$.

Pre-Viva Questions
No. Question Answer

1 What are the parameters of a The Mean ($\mu$) and the Standard
Normal Distribution? Deviation ($\sigma$).

2 What is the total area under any The total area is always 1.
PDF curve?

3 What does a high $\sigma$ It means the data is more spread out,
signify in a bell curve? making the curve flatter and wider.

4 Which distribution is often The Exponential Distribution.


called "memoryless"?

Post-Viva Questions
No. Question Answer

1 How does the Exponential curve The curve starts at a higher point
change if $\lambda$ increases? on the y-axis ($y = \lambda$) and
decays much faster.
2 Why did we use subplot(2,1,1) and To stack the two graphs vertically (2
subplot(2,1,2)? rows, 1 column) for easier
comparison.

3 What happens to the Normal curve if The shape remains exactly the
$\mu$ is changed? same, but the entire curve shifts left
or right along the x-axis.

4 What is the significance of the y(x < 0) = It ensures the Exponential PDF
0 line in your code? follows its mathematical definition,
where probability is zero for any
time less than zero.

Experiment No. 12
Experiment Title
Solving a Linear Programming Problem (LPP) of three variables using the Simplex
Method.

Relevant CO
CO: Apply iterative optimization algorithms to solve multi-variable linear
programming problems and interpret the final basis for decision making.

Objective
To determine the values of decision variables $x_1$ and $x_2$ that maximize the
objective function $Z$ subject to a set of linear constraints using the Simplex Method.

Apparatus Used
●​ Manual Calculation: Paper, pen, and calculator.
●​ Software (Optional): Scilab (using the linpro or optim functions).

Theory
The Simplex Method is an iterative procedure for solving linear programming
problems. It starts at a feasible corner point (usually the origin) and moves along the
edges of the feasible region to an adjacent corner point that improves the value of the
objective function.

Key Concepts:
●​ Objective Function: The function we want to maximize (e.g., $Z = 3x_1 + 5x_2$).
●​ Slack Variables ($s_1, s_2, s_3$): Added to "$\le$" constraints to convert
inequalities into equations. They represent unused resources.
●​ Standard Form: A version of the problem where all constraints are expressed
as equalities and all variables are non-negative.
●​ Pivot Element: The intersection of the entering column (most negative $Z_j -
C_j$) and the leaving row (minimum positive ratio).

Code (Handwritten Formulation)


Based on the provided notes, the problem is formulated as follows:

1. Objective Function:

Maximize $Z = 3x_1 + 5x_2 + 0s_1 + 0s_2 + 0s_3$

2. Constraints in Standard Form:

●​ $x_1 + s_1 = 4$
●​ $2x_2 + s_2 = 12$
●​ $3x_1 + 2x_2 + s_3 = 18$
●​ Where $x_1, x_2, s_1, s_2, s_3 \ge 0$

3. Initial Simplex Table:

Basis x1​ x2​ s1​ s2​ s3​ RHS Ratio

$s_1$ 1 0 1 0 0 4 -

$s_2$ 0 2 0 1 0 12 12/2 = 6

$s_3$ 3 2 0 0 1 18 18/2 = 9

$Z$ -3 -5 0 0 0 0 -

Result
After completing the iterations (as indicated by the final values on your note), the
optimal solution is reached when all values in the $Z$-row are non-negative.

●​ Optimal Value of $x_1$: 2


●​ Optimal Value of $x_2$: 6
●​ Maximum Value of $Z$: 36

Inference and Precautions


Inference:

The Simplex Method successfully optimized the resource allocation. We found that
the maximum profit (or utility) $Z = 36$ is achieved by producing 2 units of $x_1$ and
6 units of $x_2$. At this point, the first and third constraints are fully utilized (slack
variables $s_1$ and $s_3$ are zero), while the second constraint is also at its limit.

Precautions:

1.​ Standard Form: Ensure all inequalities are correctly converted to equalities by
adding slack variables.
2.​ Minimum Ratio Rule: When selecting the leaving variable, always choose the
smallest non-negative ratio to maintain feasibility.
3.​ Tie-Breaking: If two ratios are equal, any one can be chosen as the pivot row,
but care must be taken to avoid cycling.
4.​ Non-Negativity: Always verify that the final values of the decision variables are
$\ge 0$.

Pre-Viva Questions
No. Question Answer

1 What is a "Slack Variable"? A variable added to a "less than or equal to"


constraint to turn it into an equality. It
represents unused capacity.

2 What is a "Basic Feasible A solution where the number of non-zero


Solution" (BFS)? variables equals the number of constraints,
and all variables are $\ge 0$.

3 When does the Simplex For a maximization problem, it stops when all
algorithm terminate? coefficients in the $Z$-row (objective function
row) are non-negative.
4 What is the difference Decision variables ($x_1, x_2$) are the
between decision variables primary outputs, while slack variables ($s_1,
and slack variables? s_2$) represent idle resources.

Post-Viva Questions
No. Question Answer

1 What does a $Z$ value of It is the maximum possible value the objective
36 signify in this function can achieve given the constraints.
problem?

2 What happens if a We would subtract a surplus variable and add an


constraint is $x_1 \ge 4$? artificial variable (using Big-M or Two-Phase
method).

3 How do you identify the Look for the variable in the $Z$-row with the most
"Entering Variable"? negative value.

4 What is a "Degenerate" A situation where one or more basic variables in


solution? the final solution have a value of zero.

Experiment No. 13
Experiment Title
Solve an Assignment problem of three/four variables using the Hungarian Method
logic.

Relevant CO
CO13: Solve assignment problems to minimize total cost or time by ensuring a
one-to-one mapping between tasks and resources.

Objective
To write and execute a Scilab program that:

1.​ Accepts a square cost matrix.


2.​ Applies row and column reduction techniques (Hungarian logic).
3.​ Determines an optimal assignment where each job is assigned to exactly one
machine/worker.
4.​ Calculates the total minimum cost of the assignment.

Apparatus Used
●​ Software: Scilab (Version 2025.0.0)
●​ Hardware: Personal Computer / Laptop

Theory
The Assignment Problem is a special case of the Transportation Problem where the
objective is to assign $n$ items (jobs) to $n$ other items (machines) on a one-to-one
basis such that the total cost is minimized.

The Hungarian Method is the most efficient algorithm for this:

1.​ Row Reduction: Subtract the smallest element of each row from every element
in that row.
2.​ Column Reduction: Subtract the smallest element of each column from every
element in that column.
3.​ Optimal Assignment: Search for zeros in the reduced matrix. An assignment is
made at a zero position $(i, j)$ if no other assignment has been made in row $i$
or column $j$.
4.​ Total Cost: The sum of the costs in the original matrix corresponding to the
assigned zero positions.

Code (Scilab Script)


Scilab
clc;
clear;

// Original Cost Matrix (4x4 example)


C = [9 2 7 8;
6 4 3 7;
5 8 1 8;
7 6 9 4];

original_C = C;
n = size(C, 1);

// Step 1: Row reduction


for i = 1:n
C(i,:) = C(i,:) - min(C(i,:));
end

// Step 2: Column reduction


for j = 1:n
C(:,j) = C(:,j) - min(C(:,j));
end

disp("Reduced Cost Matrix:");


disp(C);

// Step 3: Assignment Logic (Greedy Approach)


X = zeros(n,n);
row_assigned = zeros(n,1);
col_assigned = zeros(n,1);

for i = 1:n
for j = 1:n
if C(i,j) == 0 & row_assigned(i)==0 & col_assigned(j)==0 then
X(i,j) = 1;
row_assigned(i) = 1;
col_assigned(j) = 1;
end
end
end

disp("Assignment Matrix (1 indicates assignment):");


disp(X);

// Calculate total cost using the original matrix


total_cost = sum(sum(X .* original_C));

disp("Total Minimum Cost:");


disp(total_cost);

disp("Name: Manav Singh");


disp("06213202723");

Result
The program was executed with the $4 \times 4$ cost matrix.

●​ The Reduced Cost Matrix was generated after performing row and column
subtractions.
●​ The Assignment Matrix showed that each row was assigned to a unique
column (where $X_{ij}=1$).
●​ Total Minimum Cost: Calculated as the sum of original costs at the assigned
positions.

Inference and Precautions


Inference:

The Hungarian method logic effectively reduces a complex cost matrix to a set of
"opportunity costs." By identifying zeros in the reduced matrix, we find the most
cost-effective way to distribute tasks. This experiment proves that even for
multi-variable problems, row/column operations can reveal the optimal one-to-one
mapping.

Precautions:

1.​ Square Matrix: Ensure the number of rows equals the number of columns. If
not, add a dummy row or column with zero costs.
2.​ Original Costs: Always calculate the final total cost using the original matrix,
not the reduced one.
3.​ Conflict Check: During the assignment phase, ensure that once a zero in a row
is chosen, no other zero in that same row or column is selected.
4.​ Zero Availability: If a complete assignment cannot be made with the initial
zeros, further "line drawing" steps (Hungarian Step 3) would be required for
more complex matrices.

Pre-Viva Questions
1.​ What is an Assignment Problem? It is a problem of finding a one-to-one match
between two sets (like workers and jobs) to minimize total cost.
2.​ Can we solve an assignment problem using the Simplex method? Yes, because
it is a special type of Linear Programming Problem, but the Hungarian method
is much faster.
3.​ What is a "Dummy" row/column? It is a row or column of zeros added to a
non-square matrix to make it square ($n \times n$).
4.​ What is the objective of Row Reduction? To create at least one zero in every
row.

Post-Viva Questions
1.​ What does a '0' in the reduced matrix represent? It represents an "opportunity
cost" of zero, indicating a potential optimal assignment.
2.​ How do you calculate the final cost? By summing the values from the original
cost matrix at the locations where assignments (1s) were made.
3.​ Why must each row and column have only one assignment? Because the
constraint is that one resource can perform only one task.
4.​ Is the solution to an assignment problem always unique? Not necessarily; if
multiple zeros are available in reduced rows/columns, there might be multiple
optimal assignments with the same minimum cost.

Here is the complete content for Experiment No. 10.


Experiment No. 10

Experiment Title
Fitting of normal distribution when parameters (Mean, Standard Deviation, and Total Frequency) are
given.

Relevant CO
CO10: Analyze continuous probability models and evaluate expected frequencies to predict behavior in
large-scale engineering systems.

Objective
To write and execute a Scilab program that:

1.​ Accepts the parameters μ (Mean), σ (Standard Deviation), and N (Total Frequency).
2.​ Calculates the theoretical probabilities for a range of values using the Normal PDF.
3.​ Determines the expected frequencies (fe​) for the distribution.
4.​ Plots the resulting "Bell Curve" to visualize the distribution.

Apparatus Used
●​ Software: Scilab (Version 2025.1.0)
●​ Hardware: Personal Computer / Laptop

Theory
The Normal Distribution is a continuous probability distribution that is symmetrical about the mean. It is
defined by two parameters: the Mean (μ), which locates the center of the peak, and the Standard
Deviation (σ), which determines the spread.

The Probability Density Function (PDF) is given by:

f(x)=σ2π ​1​e−21​(σx−μ​)2

To fit the distribution to a total frequency N, the expected frequency for any point x is:

fe​=N×f(x)
Opens in a new windowGetty Images
Standard normal distribution, standard deviation and coverage in statistics

Key characteristics include:

●​ The curve is bell-shaped and symmetric about x=μ.


●​ The mean, median, and mode are all equal.
●​ The total area under the curve is exactly 1.

Code (Scilab Script)


Scilab
clc;
clear;

// Input Parameters
mu = input("Enter the Mean (mu): ");
sigma = input("Enter the Standard Deviation (sigma): ");
N = input("Enter the Total Frequency (N): ");

// Defining range of x (usually 3 sigma on either side of mean)


x = (mu - 3*sigma) : 0.5 : (mu + 3*sigma);

// Calculating Expected Frequencies


for i = 1:length(x)
val = x(i);
// Normal PDF formula scaled by N
p = (1 / (sigma * sqrt(2 * %pi))) * exp(-((val - mu)^2) / (2 * sigma^2));
f_expected(i) = N * p;
end

disp("X values used:", x);


disp("Calculated Expected Frequencies:", f_expected);
// Graphical Visualization
clf();
plot(x, f_expected, "o-r"); // Red line with circles
xtitle("Fitting of Normal Distribution");
xlabel("X (Observations)");
ylabel("Expected Frequency (fe)");
grid on;

disp("Name: Sanyam Nagpal");


disp("02613202724");

Result
The program was executed with sample parameters (e.g., μ=50, σ=5, N=100). The output generated a
smooth, symmetrical bell curve centered at 50. The calculated expected frequencies showed that the
highest frequency occurs at the mean, tapering off as we move further away toward μ±3σ.

Inference and Precautions


Inference: We successfully modeled a continuous dataset using the Normal distribution. The experiment
demonstrates that if we know the mean and standard deviation of a process, we can accurately predict
how often certain values will occur. This is essential for quality control and error analysis in electronics.

Precautions:

1.​ Range Selection: Always set the range of x to at least 3 standard deviations from the mean to
capture 99.7% of the data.
2.​ Constant Precision: Use the built-in %pi in Scilab for the value of π to avoid rounding errors.
3.​ Step Size: Use a small step size (like 0.5 or 0.1) in the x range to ensure the plot looks like a
smooth curve rather than a series of jagged lines.
4.​ N Factor: Remember that the PDF only gives probability; you must multiply by N to get the actual
frequency.

Pre-Viva Questions
No. Question Answer

1 What is another name for the Normal It is commonly known as the Gaussian Distribution.
distribution?

2 What are the two parameters that define The Mean (μ) and the Standard Deviation (σ).
a Normal curve?

3 What is the total area under the Normal The total area is always 1.
PDF curve?

4 What is a "Standard Normal It is a special case where the mean (μ) is 0 and the
Distribution"? standard deviation (σ) is 1.

Export to Sheets
Post-Viva Questions
No. Question Answer

1 How does the curve change if σ is The curve becomes flatter and wider, showing that the
increased? data is more spread out.

2 What percentage of data falls within Approximately 68% of the data.


±1σ of the mean?

3 Why did we use the exp() function in To calculate e raised to the power of the exponent in the
the code? Normal distribution formula.

4 Where does the peak of the Normal The peak always occurs exactly at the Mean (μ).
curve occur?

Export to Sheets

Experiment No. 2

Experiment Title
To find the factorial of a Natural Number using Scilab.

Relevant CO
CO2: Apply basic mathematical algorithms and iterative control structures (loops) to solve algebraic
problems.

Objective
To write and execute a Scilab program that:

1.​ Accepts a natural number n from the user.


2.​ Calculates the factorial (n!) using an iterative loop.
3.​ Displays the final result in the console.

Apparatus Used
●​ Software: Scilab (Version 2025.1.0)
●​ Hardware: Personal Computer / Laptop

Theory
The Factorial of a non-negative integer n is the product of all positive integers less than or equal to n. It
is denoted by n!.

Mathematical Formula:

n!=n×(n−1)×(n−2)×⋯×1
Special Cases:

●​ 0!=1
●​ 1!=1

In programming, we calculate this by initializing a variable (usually fact) to 1 and then multiplying it by
every integer from 1 up to n using a for or while loop.

ShutterstockExplore

Code (Scilab Script)


Scilab
clc;
clear;

// Taking input from the user


n = int(input("Enter a natural number: "));

// Initializing factorial variable


fact = 1;

if (n < 0) then
disp("Factorial is not defined for negative numbers.");
else
// Loop to calculate factorial
for i = 1:n
fact = fact * i;
end

disp("The factorial of " + string(n) + " is:");


disp(fact);
end

disp("Name: Sanyam Nagpal");


disp("02613202724");

Result
The program was successfully executed.

●​ Input: 5
●​ Output: 120
●​ Input: 0
●​ Output: 1 The logic correctly handled both standard natural numbers and the special case of
zero.

Inference and Precautions

Inference: Through this experiment, we learned how to use a for loop to perform repetitive
multiplications. This iterative approach is more memory-efficient than recursion for simple tasks in
Scilab. We also observed how variables can "accumulate" values over multiple iterations.

Precautions:

1.​ Initialization: The fact variable must be initialized to 1. Initializing it to 0 would result in the
entire product being 0.
2.​ Negative Numbers: Factorials are only defined for non-negative integers; the code should
include a check for negative inputs.
3.​ Data Types: For very large numbers, factorials grow extremely fast. Be aware that very high
inputs may exceed the standard integer limit (overflow).
4.​ Loop Range: Ensure the loop runs from 1 to n inclusive.

Pre-Viva Questions
No. Question Answer

1 What is the value of 0!? The value is 1.

2 Which loop is better for this A for loop is generally better because we know the exact
program, for or while? number of iterations (1 to n).
3 Why do we initialize fact = 1 Because any number multiplied by 0 is 0. We need 1 as the
instead of fact = 0? multiplicative identity.

4 What is a "Natural Number"? Natural numbers are positive integers (1,2,3,…), though in
programming we often include 0 for factorial logic.

Export to Sheets

Post-Viva Questions
No. Question Answer

1 Is there a built-in function in Yes, the function is factorial(n).


Scilab for factorials?

2 What happens if you enter a Scilab will likely return the result in scientific notation (e.g.,
large number like 100? 9.332E+157) due to the massive size of the number.

3 How can you modify the code Initialize i = 1, use while (i <= n), and remember to
to use a while loop? increment i = i + 1 inside the loop.

4 What is the time complexity of The time complexity is O(n), as the loop runs exactly n times.
this iterative algorithm?

You might also like