XJEL1703 – Algorithms andNumerical Mathematics

洛雨听花發表於2024-12-08

XJEL1703 – Algorithms andNumerical MathematicsRoots Finding, Linear and Polynomial Regression, Interpolation, Integration – Assignment 2School of Electronic & Electrical Engineering

XJEL1703 – Algorithms and Numerical Mathematics Roots Finding, Linear and Polynomial Regression, Interpolation, Integration – Assignment 2Report 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 thisassignment in order to pass the module, regardless of your scoreon 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) ..................................................................................................................................... 10Page 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 howto make functions, vary parameters in them and display andanalyse your results.In this assignment you will also be required to write codes which vary different input parameters of functionsthat 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 particularlines do, and you should also provide a sentence or two explaining the entire algorithm and your codestructure in the report.
  1. Observatory comments – these comments describe what you can observe from your results. They aretypically 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
  1. 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 explainit? 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 variousplotting function along with plot, and the important ones are loglog, semilogx and semilogy which scale oneof the axes or both of them logarithmically. These plotting functions are useful when your inputs are notequidistant, and have rapidly increasing or decreasing values (forinstance powers of 10). In the followingquestions you will be instructed when to use a specific plot function, however you may, for your own merit, tryconclusions as in logarithmic plot.Note that even though you are allowed to copy-paste specific functions from the notes and use them, you stillneed 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 2The following example illustrates analysis of function with multiple inputs. Imagine you were provided with afunction that evaluates exponential of x, with specified tolerance tol, the function also returns number ofiterations needed to satisfy the tolerance tol. Analysis of such function would require you to do the following:%Analysis of xx=linspace(0,10); % needs to be varied

tol=1e-6; % needs to be fixedfor i=1:length(x)y_x(i) itt_x(i)]=custom_exp_fun(x(i),tol);enderror_x=abs(y_x-exp(x)); % you should have something to compare with%Analysis of tolerancex_fixed=5; % needs to be fixed

tolerance=10.^(-16:-1); % needs to be variedfor i=1:length(tolerance)[y_tol(i) itt_tol(i)]=custom_exp_fun(x_fixed,tolerance(i));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 orsemilogy function while plots (tolerance,error_tol) and (itt_tol,error_tol) should be plotted with semilogx orloglog function 代寫XJEL1703 – Algorithms andNumerical Mathematics 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 .mfiles. In the assignment you will always beasked to do it separately. If, in future, you are required to the similar analysis in different type of problem, makesure that you do not overwrite variables used in previous variation of input parameters (make sure your maincode always clears the memory).Some of the functions you areprovided 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 previousassignments 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 symbolicx=linspace(-10,10); % this is x – axis, it did not overwrite x in the previousfunction!ylot(x,y); %this will plot function F for input xf% you may call other function that needs function inputConstruct @(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.Inmany 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. DemicXJEL1703 –Algorithms and Numerical Mathematics 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 calledhowever you could not use fzero function on it, because y_array2 is an array, and fzero needs a function as annput.

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 ofthese. Bracketing methods such as the bisection methodrequire two initial conditions on either side of the rootof a continuous function such that they have opposite signs. The interval is then repeatedly bisected until theroot is found within some tolerance. False position bracketing method determines the next guess not bysplitting the bracket in half but by connecting the endpoints with a straight line and determining the location ofthe 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. DemicXJEL1703 – Algorithms and Numerical Mathematics Roots Finding, Linear and Polynomial Regression, Interpolation, Integration – Assignment 2Question 1. (15 marks)

1.1. Using the code for the bisection method provided in Lecture 2 calculate the real rootsof the function f(x) = x4 -2x - 2 using 5 iterations. To determine the intervals where thefunction 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 functionven in 1.1 to an error value less than the provided parameter namedtolerance andeturns the number of bisection iterations necessary for convergence.The modificationrequires 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 valueswith bisection method Focus on one of the roots and plot number of iterations vs range of tolerance values

XJEL1703 – Algorithms and Numerical Mathematics Roots Finding, Linear and Polynomial Regression, Interpolation, Integration – Assignment 22.2. Read about Matlab built-in fzero program (use command help fzero in thecommand 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 givefunctionautomatically. In order to do this you need to make array for the x-axis and send eachpoint of x(i) as initial guess to mynewtontol function, your output (the roots) will also bean array. Use tolerance of 1×10-6 .do you have repetitive roots? Check MATLAB’s round and unique function and combinethem 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 initialguessonly when your function changes sign doing, therefore, the incremental searchalgorithm 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 tocheck where the root is.

- Discuss incremental search and bracketing procedure and what are potentialproblems. Illustrate potential incremental search hazards plotting inMATLABdifferentfunctions of your choice.(10 marks)2.4Write a MATLAB program that determines how many iterations Newton’s method takeso have the tolerance 1×10-6 with various initial values for the root x. You will need tomake x-axis array, send it to mynewtontol function and output number of iterations foevery guess x(i).

- Test your code for the function f(x) = x4 - 2x - 2 and plot number of iterations neededfor different guesses. What do you notice? - Review the theory of Newton’s - Test your code for the function f(x) = x2 - 2x +1 and repeat the procedure you did withthe previous function. What do you notice now? Formulate mathematical condition when the issue you noticed with the first function occurs. (7 marks)Page 8 of 12 Dr D Indjin and Dr A. Demic

XJEL1703 – Algorithms and Numerical Mathematics method, for bisection method choose interval [1 3]. Plot (use semilogx function) number of iterations needed fordifferent tolerances obtained from bothmethods on the same graph. What do you notice?

(3 marks) Function fitting - linear and nonlinear regressionDetermining the relationship between variables involved in a process is often an important part of engineering.f an engineer is required to develop an understanding of underlying mechanisms or is attempting to optimise ad mathematical expression that describes theexperimental data is called an approximating function. There arewo approaches to determining an approximating function:-The approximating function graphs as a smooth curve. In this case, the plotted curve will generally notpass through all the data points, but we seek to minimize the resulting error to get the best fit. A plot ofthe data on linear, semilog, or log-log coordinates can often suggest an appropriate form for theapproximating function.- Theapproximating function passes through all data points. However, if there is some scatter in thedata points, this approximating function may not be satisfactory.Question 3. (10 marks) 1x to this data and find coefficients a0 and a1 by using mylinregr fromyour notes. Plot (use stem function) original data y(x) and the linear fit (use plotfunction) on thesame 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 thirdfourth 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 eachpolynomial fit.

(5 marks)Page 9 of 12 Dr D Indjin and Dr A. DemicXJEL1703 – Algorithms and Numerical Mathematics Roots Finding, Linear and Polynomial Regression, Interpolation,Integration – Assignment 2Interpolation Question 4. (20 marks) Using inverse interpolation technique based on the Lagrange interpolation and amethod 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):

  1. 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 andquadratic regression will anticipate same populations. Plot inverse interpolation function

for different years.(10 marks)Page 10 of 12 Dr D Indjin and Dr A. DemicXJEL1703 – 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. Voltagefluctuations impact sensitive electronics and increase wear on infrastructure. Engineers need robust methodsfor 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)

Task 1: Polynomial Regression and Signal Smoothing (10 marks)

  1. Polynomial Regression: Fit polynomial regression models of the 3rd, 4th, and 5th degrees to thevoltage data using MATLAB’s polyfit and polyval functions. Plot each polynomial fit with the originaldata to determine which model best represents voltage trends overtime.Plot: Original voltage data (scatter or stem plot) and polynomial regression curves (3rd, 4th, and 5thdegree) on the same graph.Page 11 of 12 Dr D Indjin and Dr A. DemicXJEL1703 – Algorithms and Numerical Mathematics Roots Finding, Linear and Polynomial Regression, Interpolation, Integration – Assignment 2
  1. Residual Analysis: Calculate and plot the residuals (errors) for each polynomial fit to analyse whichdegree most accurately captures voltage variations. Identify which model most effectively handlesfluctuations and discuss the potential effects of overfitting.Plot: Separate plot showing residuals for each polynomial degree (3rd, 4th, and 5th) against time.
  1. 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 controlsystem decisions for grid stability.Plot: Plot the best-fitting polynomial regression model at half-hour intervals (a smoothed version of thevoltage curve).Task 2: Root Finding and Threshold-Based Voltage Control (10 marks)Threshold Root Finding: Set a critical voltage threshold at 215 V, below which the grid’s stability iscompromised. Using root-finding methods (bisection and falseposition), determine the precise timeswhen the voltage crosses this threshold.Plot: Original voltage data with a horizontal line at the critical threshold of 215 V. Mark points where thevoltage crosses this threshold were found using root-finding methods.
  1. Tolerance vs. Iterations Analysis: For both the bisection and false position methods, vary thetolerance levels and plot the number of iterations required to converge. Use a logarithmic scale fortolerance to analyse convergence behaviour. Discuss which method achieves faster convergence andis more suitable for grid control applications.Plot: Logarithmic plot (semiology) showing tolerance values on the x-axis and the number of iterationson the y-axis for both the bisection and false position methods.
  1. Adaptive Control Recommendation: Based on your findings, propose an optimal tolerance settingand identify the most suitable root-finding method for real-time grid monitoring. Explain how theserecommendations would improve grid reliability.Plot: Summary plot showing the times when voltage crossed the threshold for various tolerances tosupport 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 byintegrating the voltage data with the trapezoidal rule. Vary the segment count from 1 to 50 and plot theintegration error versus the number of segments to identify whetheintegration error stabilises.Plot: Semilogarithmic plot showing the number of segments on the x-axis and the integration error onthe y-axis.
  1. Romberg Integration Comparison: Apply Romberg integration for the same calculation, varying thetolerance levels to 1×10−6, 1×10−8, and 1×10−10. Plot the number of iterations for each tolerance andcompare efficiency with the trapezoidal rule.Page 12 of 12

Dr D Indjin and Dr A. DemicXJEL1703 – Algorithms and Numerical Mathematics Roots Finding, Linear and Polynomial Regression, Interpolation, Integration – Assignment Plot: Semilogarithmic plot showing tolerance on the x-axis and the number of Romberg iterationsrequired for each tolerance.

  1. Optimal Integration Method for Power Quality Monitoring: The most effective integration techniquefor continuous power quality monitoring in the grid is recommended based on error analysis andefficiency. Discuss how this could impact long-term energy management and infrastructure reliability.Plot: Comparative plot (semiology) of the trapezoidal and Rombergintegration methods, showingintegration error or iterations needed for each tolerance level.

相關文章