Numerical Algorithm Implementation: From Rule to Checked Result

Numerical Algorithm Implementation turns a mathematical procedure into calculations that a computer can repeat and check. In MATLAB, obtaining a plausible number is only part of the task: you also need to preserve the correct values during each update, decide when to stop, and explain what the returned result establishes. A scalar root calculation provides a useful model for these implementation decisions.

Specify the calculation before coding

Start by identifying the unknown, its units, the governing equation, and any physical restrictions. Write the equation in residual form:


f(x)=0.f(x)=0.


An iterate is the current approximation to the unknown. The residual is the value obtained by substituting that approximation into the equation written as zero. For a force balance, use the convention calculated force minus applied force; the residual then has units of newtons.


Suppose the supplied numerical method is Newton's method:


xk+1=xk−f(xk)f′(xk).x_{k+1}=x_k-\frac{f(x_k)}{f'(x_k)}.


Your implementation needs the residual, its derivative, an initial estimate, stopping tolerances, and an iteration limit. If xx is a displacement in metres and ff is a force in newtons, then f′f' has units of newtons per metre. Consequently, the correction f/f′f/f' has units of metres, as required.


Before division, check that the derivative is finite and nonzero. A very small derivative can also produce an excessively large correction, so candidate values need checks against the model's valid domain.

Preserve the old state until checks are calculated

The mathematical subscripts distinguish old and new values. Your variables should do the same. For a valid scalar Newton update, the essential order is:


MATLAB
xNew = x - f(x)/df(x);
step = abs(xNew - x);
rNew = f(xNew);
x = xNew;


Here, f and df represent the supplied residual and derivative calculations. Evaluate them using consistent numerical units. Reject nonfinite candidate values or residuals rather than reporting them as solutions.



Initialization matters too. Set the initial estimate and a success flag before iteration begins. Update the success flag only when the stated convergence checks pass; leaving a loop is not itself evidence of convergence.


A flow diagram shows initialization, candidate calculation, tolerance testing, and repetition or successful return.


Make the stopping policy explicit

One useful policy requires both a sufficiently small absolute step and a sufficiently small residual:


∣xk+1−xk∣≤εxand∣f(xk+1)∣≤εf.|x_{k+1}-x_k|\leq\varepsilon_x \quad\text{and}\quad |f(x_{k+1})|\leq\varepsilon_f.


The step tolerance εx\varepsilon_x has the units of xx. The residual tolerance εf\varepsilon_f has the units of ff. Their numerical values need not match. For scalar MATLAB conditions, combine the two comparisons with &&.


Step criterion met?

Residual criterion met?

Interpretation under this policy

Yes

Yes

Accept the stated numerical convergence checks.

Yes

No

Small updates have not produced an adequate equation balance.

No

Yes

The equation balance passes, but the step criterion still fails.

No

No

Continue if the update remains valid and iterations remain.


An iteration limit bounds the computational work. Reaching it should return an unsuccessful status and the latest available estimate, rather than silently converting that estimate into a converged answer.



Verify what you report

Substitute the returned estimate into the original equation, check its units and physical domain, and record why the algorithm stopped. When an independently known solution is available, compare against it to test the implementation.


Keep full precision during iteration and round only the reported result. Recheck the rounded value if rounding could materially change the residual. Report the estimate together with its convergence status and relevant diagnostics.


What to remember

  • Translate the update rule with consistent units and explicit inputs.
  • Preserve the old estimate until the step has been calculated.
  • Check the candidate residual and the specified step criterion.
  • Distinguish successful convergence from invalid arithmetic or an iteration limit.
  • Verify the returned value in the original equation.

Example: Implementing a Checked Spring-Equilibrium Solver

A nonlinear spring has restoring force


Fs(x)=(1000 N/m)x+(20000 N/m3)x3,F_s(x)=(1000\ \text{N/m})x+(20000\ \text{N/m}^3)x^3,


where xx is extension in metres. Find the extension that balances an applied force of 130 N using Newton's method. Start from x0=0.100 mx_0=0.100\ \text{m}, use an absolute step tolerance of 1.0×10−5 m1.0\times10^{-5}\ \text{m} and an absolute residual tolerance of 0.010 N0.010\ \text{N}, and allow at most 20 updates. Require both tolerances to pass, retain full precision during calculation, and report extension to six decimal places in metres.


a) Form the residual and derivative, and implement the bounded iteration in MATLAB.


Use calculated restoring force minus applied force as the residual. Differentiating with respect to extension gives the slope needed for the Newton correction:


f(x)=1000x+20000x3−130,f′(x)=1000+60000x2.\begin{aligned} f(x)&=1000x+20000x^3-130,\\ f'(x)&=1000+60000x^2. \end{aligned}


With SI numerical inputs, these return newtons and newtons per metre, respectively. The implementation preserves the old estimate until the step has been measured and marks success only when both candidate checks pass.


MATLAB
f = @(x) 1000*x + 20000*x^3 - 130;
df = @(x) 1000 + 60000*x^2;
x = 0.100;
tolX = 1.0e-5;
tolF = 0.010;
maxIter = 20;
converged = false;
iterations = 0;

for k = 1:maxIter
    r = f(x);
    slope = df(x);
    if ~isfinite(r) || ~isfinite(slope) || slope == 0
        break
    end

    xNew = x - r/slope;
    if ~isfinite(xNew)
        break
    end

    rNew = f(xNew);
    if ~isfinite(rNew)
        break
    end

    step = abs(xNew - x);
    x = xNew;
    iterations = k;

    if step <= tolX && abs(rNew) <= tolF
        converged = true;
        break
    end
end


For this spring model, the derivative is positive for every real extension. The finite-value checks still prevent invalid arithmetic from being reported as a successful answer. If the loop ends without meeting the tolerances, converged remains false.


b) Calculate the first two updates and determine whether either satisfies the stopping policy.


At the initial estimate, the spring supplies less force than the applied load:


f(x0)=1000(0.100)+20000(0.100)3−130=−10.0 N,f′(x0)=1000+60000(0.100)2=1600 N/m.\begin{aligned} f(x_0)&=1000(0.100)+20000(0.100)^3-130\\ &=-10.0\ \text{N},\\ f'(x_0)&=1000+60000(0.100)^2\\ &=1600\ \text{N/m}. \end{aligned}


The first update is


x1=0.100−−10.01600=0.106250 m.x_1=0.100-\frac{-10.0}{1600}=0.106250\ \text{m}.


Its diagnostics are


∣x1−x0∣=0.006250 m,f(x1)=1000(0.106250)+20000(0.106250)3−130=0.2392578125 N.\begin{aligned} |x_1-x_0|&=0.006250\ \text{m},\\ f(x_1)&=1000(0.106250)+20000(0.106250)^3-130\\ &=0.2392578125\ \text{N}. \end{aligned}


Both values exceed their respective tolerances. For the second update, evaluate the derivative at the stored first estimate:


f′(x1)=1000+60000(0.106250)2=1677.34375 N/m.f'(x_1)=1000+60000(0.106250)^2=1677.34375\ \text{N/m}.


Then


x2=0.106250−0.23925781251677.34375=0.1061073591057… m,∣x2−x1∣=0.0001426408943… m,∣f(x2)∣≈0.000129650413 N.\begin{aligned} x_2&=0.106250-\frac{0.2392578125}{1677.34375}\\ &=0.1061073591057\ldots\ \text{m},\\ |x_2-x_1|&=0.0001426408943\ldots\ \text{m},\\ |f(x_2)|&\approx0.000129650413\ \text{N}. \end{aligned}


The second candidate passes the residual tolerance, but its step remains greater than 0.000010 m0.000010\ \text{m}. Because the policy requires both checks, the implementation continues.


c) Calculate the next update, determine the returned status, and verify the rounded result.


Retain the unrounded second estimate when evaluating the next correction. Its derivative is approximately 1675.526299 N/m1675.526299\ \text{N/m}, giving


x3=x2−f(x2)f′(x2)≈0.1061073591057−0.0001296504131675.526299=0.1061072817268… m.\begin{aligned} x_3&=x_2-\frac{f(x_2)}{f'(x_2)}\\ &\approx0.1061073591057-\frac{0.000129650413}{1675.526299}\\ &=0.1061072817268\ldots\ \text{m}. \end{aligned}


Using the unrounded iterates, the diagnostics are


∣x3−x2∣≈7.74×10−8 m<1.0×10−5 m,∣f(x3)∣≈3.81×10−11 N<0.010 N.\begin{aligned} |x_3-x_2|&\approx7.74\times10^{-8}\ \text{m}<1.0\times10^{-5}\ \text{m},\\ |f(x_3)|&\approx3.81\times10^{-11}\ \text{N}<0.010\ \text{N}. \end{aligned}


Both criteria pass. The code returns converged = true and iterations = 3. Rounding only the final reported extension gives


x=0.106107 m.x=0.106107\ \text{m}.


Check the rounded value in the original force balance:


Fs(0.106107)=1000(0.106107)+20000(0.106107)3≈129.999528 N,f(0.106107)≈−0.000472 N.\begin{aligned} F_s(0.106107)&=1000(0.106107)+20000(0.106107)^3\\ &\approx129.999528\ \text{N},\\ f(0.106107)&\approx-0.000472\ \text{N}. \end{aligned}


The rounded value remains positive, lies in the extension domain, and has residual magnitude below 0.010 N. Report 0.106107 m, with successful convergence after three updates under the stated stopping policy.

A MATLAB solver stores a displacement estimate as x = 0.160, in metres. It has calculated the next estimate as xNew = 0.205, also in metres. Which fragment correctly records the absolute step and stores the new estimate for the next iteration?

Choose an answer

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

A MATLAB routine solves an engineering heat-balance equation. Its iteration limit is the maximum permitted number of updates, set here to 20. After each update, the routine checks for invalid evaluations before testing convergence.


The supplied residual function returns NaN whenever a trial temperature falls outside its permitted range of 0–200 °C. A result is accepted only when both the residual and update satisfy their specified tolerances.


Complete the reports using exactly these status labels: converged, iteration_limit, or invalid_evaluation.

  • Run R completes 20 updates with finite evaluations, but neither tolerance is satisfied. Its status is .
  • Run S proposes 217 °C on update 6, and its residual evaluation returns NaN. Its status is .

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

A nonlinear spring has restoring force


Fs(x)=(500 N/m)x+(40000 N/m3)x3,F_s(x)=(500\ \text{N/m})x+(40000\ \text{N/m}^3)x^3,


where xx is its extension in metres. An applied force of 40.0 N is balanced by solving f(x)=Fs(x)−40.0 N=0f(x)=F_s(x)-40.0\ \text{N}=0.


Implement one undamped Newton update,


x1=x0−f(x0)f′(x0),x_1=x_0-\frac{f(x_0)}{f'(x_0)},


starting from x0=0.0500 mx_0=0.0500\ \text{m}. Use consistent SI numerical values and do not round intermediate calculations. What is x1x_1? Answer in metres, to four decimal places.

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

Extra Practice