XJEL1703 – Algorithms and
Numerical Mathematics Roots Finding, Linear and Polynomial Regression, Interpolation, Integration – Assignment 2
School of Electronic &
Electrical Engineering
FACULTY OF ENGINEERING
Page 2 of 12
XJEL1703 – Algorithms and Numerical Mathematics
Roots Finding, Linear and Polynomial Regression, Interpolation, Integration – Assignment 2
Report format
This assignment is split into 5 parts, questions are shaded blue, while examples (if provided) are shaded grey.
This assignment carries 70% of your total mark on the module and you need to score at least 30% on this
assignment in order to pass the module, regardless of your score on the previous two assignments.
- Answer all the questions in separate document (your report), include your name and student number.
- Make your report as organized as you can (e.g use tables for short questions, different colours, fonts
etc.).
- For questions where you do something in MATLAB command line you must copy-paste input/output
from MATLAB to your report – you can do this directly (copy-paste) or take a print screen and paste
a picture.
- For questions which require you to write a code you should take a photo (snipping tool or print screen)
of your code in the report (or copy paste it) and also upload corresponding .m file along your report.
Also add comments into codes (using MATLAB symbol % ) and explain what lines in your code do in
the report.
- You should also add comments explaining what you did and notify anything you found peculiar in
MATLAB (and give an opinion why that happened).
Contents
Roots Finding Algorithms ...................................................................................................................................... 5
Question 1. (15 marks) ....................................................................................................................................... 6
Question 2. (25 marks) ....................................................................................................................................... 6
Function fitting - linear and nonlinear regression .................................................................................................. 8
Question 3. (10 marks) ....................................................................................................................................... 8
Interpolation ........................................................................................................................................................... 9
Question 4. (20 marks) ....................................................................................................................................... 9
Optimising Voltage Stability and Energy Management in a Smart Grid: A MATLAB-Based Analysis ........ 10
Question 5. (30 marks) ..................................................................................................................................... 10
Page 3 of 12
Dr D Indjin and Dr A. Demic
XJEL1703 – Algorithms and Numerical Mathematics
Roots Finding, Linear and Polynomial Regression, Interpolation, Integration – Assignment 2
Assignment hints
This assignment primarily focuses on testing your analytic skills. In the previous assignment you learned how
to make functions, vary parameters in them and display and analyse your results.
In this assignment you will also be required to write codes which vary different input parameters of functions
that we will provide and analyse effect of those parameters, thus your comments are primarily marked.
Generally, there are three types of comments you could make:
1. Code comments – these comments should be present in the codes itself explaining what particular
lines do, and you should also provide a sentence or two explaining the entire algorithm and your code
structure in the report.
2. Observatory comments – these comments describe what you can observe from your results. They are
typically not worth many marks, but are a necessary part of your work. For instance in Assignment 1,
you might’ve commented on graph error vs terms: “The numerical error flattens for 20-30 terms in the
expansion when x is fixed to 5” or “fzero is MATLAB’s function that finds a root of a function that is
closest to the initial guess”
3. Explanatory comments – these comments explain your results, most likely after some observation.
They are worth the most marks. Anyone can observe some peculiarity on a graph, but can you explain
it? For example in Assignment 1, an explanatory comment would be: “Numerical error decreases with
number of terms, however it displays saturation effect when error reaches the scale of 1e-16. This
saturation effect is purely of numerical nature as 1e-16 is the smallest number MATLAB can represent
by the default data type we are using, while theoretically the error should still be decreasing with
addition of more terms in the Maclaurin expansion”.
It is important to have sense of displaying your data. Matlab’s plot function links data points (x,y) linearly, so if
you have a lot of points, your graph would be smooth, you can use stem function to display points only
(without linking them linearly) which is recommended if your data has only few points. Matlab has various
plotting function along with plot, and the important ones are loglog, semilogx and semilogy which scale one
of the axes or both of them logarithmically. These plotting functions are useful when your inputs are not
equidistant, and have rapidly increasing or decreasing values (for instance powers of 10). In the following
questions you will be instructed when to use a specific plot function, however you may, for your own merit, try
using plot in order to see the difference, and more importantly to check whether you can derive same
conclusions as in logarithmic plot.
Note that even though you are allowed to copy-paste specific functions from the notes and use them, you still
need to include them in your report and Minerva submission.
Page 4 of 12
Dr D Indjin and Dr A. Demic
XJEL1703 – Algorithms and Numerical Mathematics
Roots Finding, Linear and Polynomial Regression, Interpolation, Integration – Assignment 2
The following example illustrates analysis of function with multiple inputs. Imagine you were provided with a
function that evaluates exponential of x, with specified tolerance tol, the function also returns number of
iterations needed to satisfy the tolerance tol. Analysis of such function would require you to do the following:
%Analysis of x
x=linspace(0,10); % needs to be varied
tol=1e-6; % needs to be fixed
for i=1:length(x)
[y_x(i) itt_x(i)]=custom_exp_fun(x(i),tol);
end
error_x=abs(y_x-exp(x)); % you should have something to compare with
%Analysis of tolerance
x_fixed=5; % needs to be fixed
tolerance=10.^(-16:-1); % needs to be varied
for i=1:length(tolerance)
[y_tol(i) itt_tol(i)]=custom_exp_fun(x_fixed,tolerance(i));
end
error_tol=abs(y_tol-exp(x));
The next step would be plotting these results. Plots (x,error_x) and (x,itt_x) should be done with plot or
semilogy function while plots (tolerance,error_tol) and (itt_tol,error_tol) should be plotted with semilogx or
loglog function since the x-axis in the plot is logarithmic, and y-axis is error which is usually very small.
Note that analysis of different inputs should ideally be in different .m files. In the assignment you will always be
asked to do it separately. If, in future, you are required to the similar analysis in different type of problem, make
sure that you do not overwrite variables used in previous variation of input parameters (make sure your main
code always clears the memory).
Some of the functions you are provided for this assignment request function input in order to work properly,
namely zero finding functions and interpolation functions. You may have noticed how to do that in the previous
assignments by making a function file, however Matlab has a neat trick how to construct an inline function
handler:
F=@(x) x.^2 – 5*x + 5; % this is a function of x, where x is symbolic
x=linspace(-10,10); % this is x – axis, it did not overwrite x in the previous
function!
y=F(x); % this will place array x into your function and evaluate
plot(x,y); % this will plot function F for input x
fzero(F,5); % you may call other function that needs function input
Construct @(x) means function of “x”, this approach is equivalent to making the function F in separate .m file
and it is clearly very convenient when your function is arithmetical.
The greatest advantage of this trick is that you can use it to make functions out of other functions neatly. In
many practical cases you will be provided with raw (x,y) data that you may need to interpolate and then do
Page 5 of 12
Dr D Indjin and Dr A. Demic
XJEL1703 – Algorithms and Numerical Mathematics
Roots Finding, Linear and Polynomial Regression, Interpolation, Integration – Assignment 2
some analysis (root finding, differentiation etc.). Interpolation functions usually require you to supply data and
a variable/array for which you want to find an estimate. Naturally return value is another variable/array which
you cannot use as an input to root finding function. Trick is to call interpolation function for a symbolic variable
and make its output as a function of it:
x_data=[-5 -4 -3 0 50 51 68 98]; % raw x data
y_data=[-5, -3, -0.5, 3, 8, -5, 10 20]; % raw y data
New_function = @(x) interp1(x_data,y_data,x,’cubic’); % this creates an
% interpolation function
x_array=-5:100; % create interpolating array with better spacing
y_array= New_function(x_array); % interpolation of y_data on x_array
plot(x_array,y_array) % plot of interpolated data
z1=fzero(New_function,5); % New_funciton is a function so fzero can be called
z2=fzero(New_function,80); % Find the second zero
If you interpolated your data directly as y_array2=interp1(x_data,y_data,x_array) you would be able to plot it,
however you could not use fzero function on it, because y_array2 is an array, and fzero needs a function as an
input.
Roots Finding Algorithms
The root finding algorithms covered in lectures 2 and 3 are numerical methods for finding a value x such that
f(x) = 0 for a given function f(x). These values of x are described as roots of the function f.
These methods can generally be broken down into bracketing methods, open methods, and combinations of
these. Bracketing methods such as the bisection method require two initial conditions on either side of the root
of a continuous function such that they have opposite signs. The interval is then repeatedly bisected until the
root is found within some tolerance. False position bracketing method determines the next guess not by
splitting the bracket in half but by connecting the endpoints with a straight line and determining the location of
the intercept of the straight line.
Open methods such as Newton’s method or the secant method do not require a defined interval and iteratively
calculate the derivative of the function to find the root.
In this assignment you will apply various algorithms to polynomial functions to calculate their roots.
Page 6 of 12
Dr D Indjin and Dr A. Demic
XJEL1703 – Algorithms and Numerical Mathematics
Roots Finding, Linear and Polynomial Regression, Interpolation, Integration – Assignment 2
Question 1. (15 marks)
1.1. Using the code for the bisection method provided in Lecture 2 calculate the real roots
of the function f(x) = x4
-2x - 2 using 5 iterations. To determine the intervals where the
function changes sign use the graphical method. Discuss interval width and number of
iterations.
(5 marks)
1.2. Modify your bisection method code so that the program finds the roots of the function
given in 1.1 to an error value less than the provided parameter named tolerance and
returns the number of bisection iterations necessary for convergence.
The modification requires you to set number of iterations as an output of your function,
and tolerance as an input. Check the code for false position method function in Lecture
2 notes which is already written in such format.
Write a main code where you:
- Test your modified function for 𝑡𝑡𝑡𝑡𝑡𝑡𝑡𝑡𝑡𝑡𝑡𝑡𝑡𝑡𝑡𝑡𝑡𝑡 = 10−6 and find all roots of f(x)
- Focus on one of the roots and plot number of iterations vs range of tolerance values
with bisection method
- Focus on one of the roots and plot number of iterations vs range of tolerance values
with false position method
Comment on your observation and analyse the effect of tolerance on both functions.
Hint: For making the graphs, you need to call your function for multiple values of
tolerance input. Doing this automatically (via for or while loop) is strongly
preferred. To create an array of tolerance values you may use this:
𝑡𝑡𝑡𝑡𝑡𝑡𝑡𝑡𝑡𝑡𝑡𝑡𝑡𝑡𝑡𝑡𝑡𝑡𝑡𝑡 = 10. ^(−16: −1) . This code creates array consisting of
10−16, 10−15 … 10−1 . You may also try different range as 10. ^(−20: −1) to
check what happens for very strict tolerance.
Note: Instead of saving f(x) as an inline function as suggested in the notes, you may
also use function handlers in MATLAB. You may define f(x) at the start of your
main code as: = @( ) 4 − 2 ∗ − 2. The symbol @ is called handler, (x)
means ‘function of x’.
(10 marks)
Question 2. (25 marks)
2.1. Plot the function f(x) = x4
– 2x2
+ x between -2 and 2. How many roots does this
function have? Find these roots using MATLAB roots built-in program (use command
help roots in the command window to learn more about MATLAB roots program).
(2 marks)
Page 7 of 12
Dr D Indjin and Dr A. Demic
XJEL1703 – Algorithms and Numerical Mathematics
Roots Finding, Linear and Polynomial Regression, Interpolation, Integration – Assignment 2
2.2. Read about Matlab built-in fzero program (use command help fzero in the
command window, material from Lecture 3 notes and/or on internet). Test the Matlab
program fzero finding real roots of f(x) = x4
– 2x2
+ x.
(3 marks)
2.3. Review Newton’s method function code from the lab notes. Focus on mynewtontol
function specifically and write a MATLAB code that finds all roots of the given function
automatically. In order to do this you need to make array for the x-axis and send each
point of x(i) as initial guess to mynewtontol function, your output (the roots) will also be
an array. Use tolerance of 1×10-6
.
- Use your code to find the roots of the function f(x) = x4
- 2x - 2. Plot the function for
visual check of your code. What do you notice about the output of your code? Why do
you have repetitive roots? Check MATLAB’s round and unique function and combine
them in order to filter repetitive values. What are the issues with this filtration?
- In order to avoid repetition of the roots, modify your code so that you send initial
guess only when your function changes sign doing, therefore, the incremental search
algorithm and rerun your code. What do you notice now about the output of your code?
- Furthermore test your code for the function f(x) = x2
- 2x +1. Plot the function to
check where the root is.
- Discuss incremental search and bracketing procedure and what are potential
problems. Illustrate potential incremental search hazards plotting in MATLAB different
functions of your choice.
(10 marks)
2.4. Write a MATLAB program that determines how many iterations Newton’s method takes
to have the tolerance 1×10-6
with various initial values for the root x0. You will need to
make x-axis array, send it to mynewtontol function and output number of iterations for
every guess x(i).
- Test your code for the function f(x) = x4
- 2x - 2 and plot number of iterations needed
for different guesses. What do you notice?
- Review the theory of Newton’s method and plot f(x) / f’(x). Compare this figure with
your iterations figure, what do you notice? Can you explain why this happened?
- Test your code for the function f(x) = x2
- 2x +1 and repeat the procedure you did with
the previous function. What do you notice now? Formulate mathematical condition
when the issue you noticed with the first function occurs.
Page 8 of 12
Dr D Indjin and Dr A. Demic
XJEL1703 – Algorithms and Numerical Mathematics
Roots Finding, Linear and Polynomial Regression, Interpolation, Integration – Assignment 2
2.5. Write a MATLAB program that determines how many iterations Newton’s method takes
to satisfy various tolerances tol. In this task tolerance needs to be an array (for
example from 1 to 1×10-16), while initial guess is fixed. Do this also with bisection
function code which you used in Assignment 2.
- Run your code for the function f(x) = x4
- 2x – 2, use x0 = 1 as initial guess in
Newton’s method, for bisection method choose interval [1 3]. Plot (use semilogx
function) number of iterations needed for different tolerances obtained from both
methods on the same graph. What do you notice?
(3 marks)
Function fitting - linear and nonlinear regression
Determining the relationship between variables involved in a process is often an important part of engineering.
If an engineer is required to develop an understanding of underlying mechanisms or is attempting to optimise a
device, it is useful to establish how one characteristic depends on something else such as time.
A mathematical expression that describes the experimental data is called an approximating function. There are
two approaches to determining an approximating function:
- The approximating function graphs as a smooth curve. In this case, the plotted curve will generally not
pass through all the data points, but we seek to minimize the resulting error to get the best fit. A plot of
the data on linear, semilog, or log-log coordinates can often suggest an appropriate form for the
approximating function.
- The approximating function passes through all data points. However, if there is some scatter in the
data points, this approximating function may not be satisfactory.
Question 3. (10 marks)
3.1. Given that (x,y) = (-15,-980), (-8,-620), (-6,-70), (-4,80), (-2,100), (0,90), (2,0), (4,-80),
(6,-90), (8,10), (10,225), use linear least-squares regression curve fitting approach to fit
a line y = a0 +a1x to this data and find coefficients a0 and a1 by using mylinregr from
your notes. Plot (use stem function) original data y(x) and the linear fit (use plot
function) on the same graph and discuss the accuracy of the linear fit.
(5 marks)
3.2. Repeat the curve fitting procedure as in 3.1. to find the best fit to polynomials of third,
fourth and fifth degrees using MATLAB built-in polyfit function (check polyval as well).
Plot the raw data and curves fit (on the same graph) and discuss the accuracy of each
polynomial fit.
(5 marks)
Page 9 of 12
Dr D Indjin and Dr A. Demic
XJEL1703 – Algorithms and Numerical Mathematics
Roots Finding, Linear and Polynomial Regression, Interpolation, Integration – Assignment 2
Interpolation
Question 4. (20 marks)
4.1. The population of a region between 1920 and 2000 is given in the table below. Using
Lagrange interpolation technique, determine the population in 1925. What would be the
difference between population in 1945 determined by Lagrange interpolation and
estimated by linear regression? Plot the data (stem plot), Lagrange interpolation
function and linear regression line on the same graph. Estimate what the population will
be in 2015 by Lagrange method. Is your answer reasonable? Outline the potential
hazards of extrapolation.
(10 marks)
Year Population
(millions)
1920 105
1930 120
1940 130
1950 150
1960 180
1970 205
1980 225
1990 250
2000 280
4.2. Using inverse interpolation technique based on the Lagrange interpolation and a
method for root finding by your choice (check assignment 2 for bisection, fzero or use
Newton’s method that is in question 3 of this assignment):
a) Determine year and month when the population of the region was exactly 210 million.
Plot inverse interpolation function for different years.
Hint: You want to find zero of function lagrange(x_data,y_data,x)-210, check out the hint
prior to question one.
b) Determine years (and the corresponding populations) when Lagrange interpolation and
quadratic regression will anticipate same populations. Plot inverse interpolation function
for different years.
(10 marks)
Page 10 of 12
Dr D Indjin and Dr A. Demic
XJEL1703 – Algorithms and Numerical Mathematics
Roots Finding, Linear and Polynomial Regression, Interpolation, Integration – Assignment 2
Optimising Voltage Stability and Energy Management in a Smart Grid: A
MATLAB-Based Analysis
Question 5. (30 marks)
An urban smart grid provides power under variable load conditions, affecting voltage stability. Voltage
fluctuations impact sensitive electronics and increase wear on infrastructure. Engineers need robust methods
for forecasting voltage trends, identifying critical thresholds, and optimising control settings.
Below is voltage data recorded hourly over 24 hours under varying load demands:
Time (hours) Voltage (V)
0 230
1 225
2 220
3 218
4 215
5 210
6 205
7 208
8 212
9 217
10 222
11 227
12 230
13 235
14 240
15 238
16 234
17 230
18 228
19 226
20 224
21 223
22 221
23 220
24 218
Task 1: Polynomial Regression and Signal Smoothing (10 marks)
1. Polynomial Regression: Fit polynomial regression models of the 3rd, 4th, and 5th degrees to the
voltage data using MATLAB’s polyfit and polyval functions. Plot each polynomial fit with the original
data to determine which model best represents voltage trends over time.
Plot: Original voltage data (scatter or stem plot) and polynomial regression curves (3rd, 4th, and 5th
degree) on the same graph.
Page 11 of 12
Dr D Indjin and Dr A. Demic
XJEL1703 – Algorithms and Numerical Mathematics
Roots Finding, Linear and Polynomial Regression, Interpolation, Integration – Assignment 2
2. Residual Analysis: Calculate and plot the residuals (errors) for each polynomial fit to analyse which
degree most accurately captures voltage variations. Identify which model most effectively handles
fluctuations and discuss the potential effects of overfitting.
Plot: Separate plot showing residuals for each polynomial degree (3rd, 4th, and 5th) against time.
3. Control System Smoothing: For the best-fitting polynomial, use it to predict voltage values at halfhour
intervals (e.g., 0.5, 1.5, etc.). Comment on how this finer resolution could improve real-time control
system decisions for grid stability.
Plot: Plot the best-fitting polynomial regression model at half-hour intervals (a smoothed version of the
voltage curve).
Task 2: Root Finding and Threshold-Based Voltage Control (10 marks)
1. Threshold Root Finding: Set a critical voltage threshold at 215 V, below which the grid’s stability is
compromised. Using root-finding methods (bisection and false position), determine the precise times
when the voltage crosses this threshold.
Plot: Original voltage data with a horizontal line at the critical threshold of 215 V. Mark points where the
voltage crosses this threshold were found using root-finding methods.
2. Tolerance vs. Iterations Analysis: For both the bisection and false position methods, vary the
tolerance levels and plot the number of iterations required to converge. Use a logarithmic scale for
tolerance to analyse convergence behaviour. Discuss which method achieves faster convergence and
is more suitable for grid control applications.
Plot: Logarithmic plot (semiology) showing tolerance values on the x-axis and the number of iterations
on the y-axis for both the bisection and false position methods.
3. Adaptive Control Recommendation: Based on your findings, propose an optimal tolerance setting
and identify the most suitable root-finding method for real-time grid monitoring. Explain how these
recommendations would improve grid reliability.
Plot: Summary plot showing the times when voltage crossed the threshold for various tolerances to
support control system recommendations.
Task 3: Energy Estimation and Power Quality Integration (10 marks)
1. Numerical Integration for Energy: Calculate the total energy supplied by the grid over 24 hours by
integrating the voltage data with the trapezoidal rule. Vary the segment count from 1 to 50 and plot the
integration error versus the number of segments to identify when the integration error stabilises.
Plot: Semilogarithmic plot showing the number of segments on the x-axis and the integration error on
the y-axis.
2. Romberg Integration Comparison: Apply Romberg integration for the same calculation, varying the
tolerance levels to 1×10−6, 1×10−8, and 1×10−10. Plot the number of iterations for each tolerance and
compare efficiency with the trapezoidal rule.
Page 12 of 12
Dr D Indjin and Dr A. Demic
XJEL1703 – Algorithms and Numerical Mathematics
Roots Finding, Linear and Polynomial Regression, Interpolation, Integration – Assignment 2
Plot: Semilogarithmic plot showing tolerance on the x-axis and the number of Romberg iterations
required for each tolerance.
3. Optimal Integration Method for Power Quality Monitoring: The most effective integration technique
for continuous power quality monitoring in the grid is recommended based on error analysis and
efficiency. Discuss how this could impact long-term energy management and infrastructure reliability.
Plot: Comparative plot (semiology) of the trapezoidal and Romberg integration methods, showing
integration error or iterations needed for each tolerance level.
请加QQ:99515681 邮箱:99515681@qq.com WX:codinghelp