Integer type:  int32  int64  nag_int  show int32  show int32  show int64  show int64  show nag_int  show nag_int

Chapter Contents
Chapter Introduction
NAG Toolbox

# NAG Toolbox: nag_ode_ivp_rk_errass (d02pz)

## Purpose

nag_ode_ivp_rk_errass (d02pz) provides details about global error assessment computed during an integration with either nag_ode_ivp_rk_range (d02pc) or nag_ode_ivp_rk_onestep (d02pd).
Note: this function is scheduled to be withdrawn, please see d02pz in Advice on Replacement Calls for Withdrawn/Superseded Routines..

## Syntax

[rmserr, errmax, terrmx, ifail] = d02pz(neq, work)
[rmserr, errmax, terrmx, ifail] = nag_ode_ivp_rk_errass(neq, work)

## Description

nag_ode_ivp_rk_errass (d02pz) and its associated functions (nag_ode_ivp_rk_range (d02pc), nag_ode_ivp_rk_onestep (d02pd), nag_ode_ivp_rk_setup (d02pv), nag_ode_ivp_rk_reset_tend (d02pw), nag_ode_ivp_rk_interp (d02px) and nag_ode_ivp_rk_diag (d02py)) solve the initial value problem for a first-order system of ordinary differential equations. The functions, based on Runge–Kutta methods and derived from RKSUITE (see Brankin et al. (1991)), integrate
 y′ = f(t,y)  given  y(t0) = y0 $y′=f(t,y) given y(t0)=y0$
where y$y$ is the vector of n$\mathit{n}$ solution components and t$t$ is the independent variable.
After a call to nag_ode_ivp_rk_range (d02pc) or nag_ode_ivp_rk_onestep (d02pd), nag_ode_ivp_rk_errass (d02pz) can be called for information about error assessment, if this assessment was specified in the setup function nag_ode_ivp_rk_setup (d02pv). A more accurate ‘true’ solution $\stackrel{^}{y}$ is computed in a secondary integration. The error is measured as specified in nag_ode_ivp_rk_setup (d02pv) for local error control. At each step in the primary integration, an average magnitude μi${\mu }_{i}$ of component yi${y}_{i}$ is computed, and the error in the component is
 (|yi − ŷi|)/(max (μi,thres(i))). $|yi-y^i| max(μi,thres(i)) .$
It is difficult to estimate reliably the true error at a single point. For this reason the RMS (root-mean-square) average of the estimated global error in each solution component is computed. This average is taken over all steps from the beginning of the integration through to the current integration point. If all has gone well, the average errors reported will be comparable to tol (see nag_ode_ivp_rk_setup (d02pv)). The maximum error seen in any component in the integration so far and the point where the maximum error first occurred are also reported.

## References

Brankin R W, Gladwell I and Shampine L F (1991) RKSUITE: A suite of Runge–Kutta codes for the initial value problems for ODEs SoftReport 91-S1 Southern Methodist University

## Parameters

### Compulsory Input Parameters

1:     neq – int64int32nag_int scalar
n$n$, the number of ordinary differential equations in the system to be solved by the integration function.
Constraint: neq1${\mathbf{neq}}\ge 1$.
2:     work( : $:$) – double array
Note: the dimension of the array work must be at least lenwrk${\mathbf{lenwrk}}$ (see nag_ode_ivp_rk_setup (d02pv)).
This must be the same array as supplied to nag_ode_ivp_rk_range (d02pc) or nag_ode_ivp_rk_onestep (d02pd) and must remain unchanged between calls.

None.

None.

### Output Parameters

1:     rmserr( : $:$) – double array
Note: the dimension of the array rmserr must be at least n$\mathit{n}$.
rmserr(i)${\mathbf{rmserr}}\left(\mathit{i}\right)$ approximates the RMS average of the true error of the numerical solution for the i$\mathit{i}$th solution component, for i = 1,2,,n$\mathit{i}=1,2,\dots ,\mathit{n}$. The average is taken over all steps from the beginning of the integration to the current integration point.
2:     errmax – double scalar
The maximum weighted approximate true error taken over all solution components and all steps.
3:     terrmx – double scalar
The first value of the independent variable where an approximate true error attains the maximum value, errmax.
4:     ifail – int64int32nag_int scalar
${\mathrm{ifail}}={\mathbf{0}}$ unless the function detects an error (see [Error Indicators and Warnings]).

## Error Indicators and Warnings

Errors or warnings detected by the function:
ifail = 1${\mathbf{ifail}}=1$
An invalid call to nag_ode_ivp_rk_errass (d02pz) has been made, for example without a previous call to nag_ode_ivp_rk_range (d02pc) or nag_ode_ivp_rk_onestep (d02pd), or without error assessment having been specified in a call to nag_ode_ivp_rk_setup (d02pv). You cannot continue integrating the problem.

## Accuracy

Not applicable.

If the integration has proceeded ‘well’ and the problem is smooth enough, stable and not too difficult then the values returned in the arguments rmserr and errmax should be comparable to the value of tol specified in the prior call to nag_ode_ivp_rk_setup (d02pv).

## Example

This example integrates a two body problem. The equations for the coordinates (x(t),y(t))$\left(x\left(t\right),y\left(t\right)\right)$ of one body as functions of time t$t$ in a suitable frame of reference are
 x ′ ′ = − x/(r3) ,   y ′ ′ = − y/(r3),   r = sqrt(x2 + y2). $x′′=-xr3 , y′′=-yr3, r=x2+y2.$
The initial conditions
 x(0) = 1 − ε, x′(0) = 0 y(0) = 0, y′(0) = sqrt((1 + ε)/(1 − ε))
$x(0)=1-ε, x′(0)=0 y(0)=0, y′(0)= 1+ε 1-ε$
lead to elliptic motion with 0 < ε < 1$0<\epsilon <1$. ε = 0.7$\epsilon =0.7$ is selected and reposed as
 y1 ′ = y3 y2 ′ = y4 y3 ′ = − (y1)/(r3) y4 ′ = − (y2)/(r3)
$y1′=y3 y2′=y4 y3′=- y1r3 y4′=- y2r3$
over the range [0,3π]$\left[0,3\pi \right]$. Relative error control is used with threshold values of 1.0e−10$\text{1.0e−10}$ for each solution component and a high-order Runge–Kutta method (method = 3${\mathbf{method}}=3$) with tolerance tol = 1.0e−6${\mathbf{tol}}=\text{1.0e−6}$. The value of π$\pi$ is obtained by using nag_math_pi (x01aa).
Note that the length of work is large enough for any valid combination of input arguments to nag_ode_ivp_rk_setup (d02pv). Note also, for illustration purposes since it is not necessary for this problem, this example integrates to the end of the range regardless of efficiency concerns (i.e., returns from nag_ode_ivp_rk_range (d02pc) with ${\mathbf{ifail}}={\mathbf{2}}$, 3${\mathbf{3}}$ or 4${\mathbf{4}}$).
```function nag_ode_ivp_rk_errass_example
% Initialize variables and arrays.
neq = 4;
lenwrk = 32*neq;
method = 3;
ecc = 0.7;

tstart = 0.0;
ystart = [1.0-ecc; 0.0; 0.0; sqrt((1.0+ecc)/(1.0-ecc))];
tend = 3.0*pi;
thres = [1e-10; 1e-10; 1e-10; 1e-10];
errass = true;
hstart = 0.0;
tol = 1.0e-6;

fprintf('nag_ode_ivp_rk_errass example program results \n\n');

% We run through the calculation twice: once to output the results at
% a single point, and again to accumulate a series of results for plotting.
nstep = [1; 90];
tend = [3.0*pi; 2.0*pi];

% Prepare to accumulate results.  The first and last points should be the
% same - i.e. so the plot shows a closed trajectory.
xarray = zeros(nstep(2)+1, 1);
yarray = zeros(nstep(2)+1, 4);

for icalc = 1:2
tinc  = tend(icalc)/nstep(icalc);

if icalc == 1
% Output initial results.
fprintf('Calculation with tol = %1.1e\n\n',tol);
fprintf('   t         y1        y2        y3        y4\n');
fprintf(' %6.3f', tstart);
for ieq = 1:neq
fprintf('  %8.4f', ystart(ieq));
end
fprintf('\n');
else
xarray(1) = tstart;
for ieq = 1:neq
yarray(1, ieq) = ystart(ieq);
end
end

for istep = 1:nstep(icalc)
twant = istep*tinc;
% nag_ode_ivp_rk_setup is a setup routine to be called prior to nag_ode_ivp_rk_range.
[work, ifail] = nag_ode_ivp_rk_setup(tstart, ystart, twant, tol, thres, ...
int64(method), task, errass, int64(lenwrk), 'neq', ...
int64(neq), 'hstart', hstart);
if ifail ~= 0
% Unsuccessful call.  Print message and exit.
error('Warning: nag_ode_ivp_rk_setup returned with ifail = %1d ',ifail);
end

% Initialize ygot and ymax.  These values don't matter for the
% first call of nag_ode_ivp_rk_range, but they mustn't be changed in between
% calls for the same problem.
ygot = ystart;
ymax = ystart;

% In this demo, we disregard warnings about inefficiency from
% nag_ode_ivp_rk_range (i.e. ifail = 2,3 or 4 - see documentation) and keep
% calling the routine until the end of the range is reached.
ifail = 2;
while ifail >= 2 && ifail <= 4
[tgot, ygot, ypgot, ymax, work, ifail] = nag_ode_ivp_rk_range(@f, ...
int64(neq), twant, ygot, ymax, work);
% Check for other failures.
if ifail == 1 || ifail > 4
% Unsuccessful call.  Print message and exit.
error('Warning: nag_ode_ivp_rk_range returned with ifail = %1d ',...
ifail);
end
end

% Store the current result.
if icalc == 2
xarray(istep+1) = tgot;
for ieq = 1:neq
yarray(istep+1, ieq) = ygot(ieq);
end
end
end

% Output final results.
if icalc == 1
fprintf(' %6.3f', tgot);
for ieq = 1:neq
fprintf('  %8.4f', ygot(ieq));
end
fprintf('\n');

% nag_ode_ivp_rk_errass provides details about global error assessment computed
% during integration with nag_ode_ivp_rk_range (or nag_ode_ivp_rk_onestep).
[rmserr, errmax, terrmx, ifail] = nag_ode_ivp_rk_errass(int64(neq), work);
fprintf('\nComponentwise error assessment:\n        ');
for ieq = 1:neq
fprintf(' %9.2e', rmserr(ieq));
end
fprintf('\n');
fprintf(['\nWorst global error observed was %9.2e', ...
' - it occurred at T = %6.3f\n'], errmax, terrmx);

% nag_ode_ivp_rk_diag is a diagnostic routine.
[totfcn, stpcst, waste, stpsok, hnext, ifail] = nag_ode_ivp_rk_diag;
fprintf(['\nCost of the integration in evaluations of ', ...
'F is %1.0f\n\n\n'], totfcn);
end
end

% Use the first two components of the solution, and calculate the deviation
% from a true ellipse.
x = yarray(:,1);
y = yarray(:,2);
xdev = zeros(nstep(2)+1, 1);
ydev = zeros(nstep(2)+1, 1);
for i = 1:nstep(2)+1
fac = abs((x(i) + ecc)*(x(i) + ecc) + y(i)*y(i)/(ecc*ecc) - 1.0);
xdev(i) = fac*cos(xarray(i));
ydev(i) = fac*sin(xarray(i));
end
% Plot results.
fig = figure('Number', 'off');
display_plot(x, y, xdev, ydev);

function [yp] = f(t, y, yp)
% Evaluate derivative vector.

yp = zeros(4, 1);
r = sqrt((y(1)^2 + y(2)^2));
yp(1) =  y(3);
yp(2) =  y(4);
yp(3) = -y(1)/r^3;
yp(4) = -y(2)/r^3;
function display_plot(x1, y1, x2, y2)
% Formatting for title and axis labels.
titleFmt = {'FontName', 'Helvetica', 'FontWeight', 'Bold', 'FontSize', 14};
labFmt = {'FontName', 'Helvetica', 'FontWeight', 'Bold', 'FontSize', 13};
set(gca, 'FontSize', 13); % for legend, axis tick labels, etc.
% Plot the results.  First, get the list of default colours (we have to
% specify the plot colours by hand).
cols = get(gca, 'ColorOrder');
% Plot the first curve.
hline1 = line(x1, y1, 'Color', cols(1,:));
ax1 = gca;
set(ax1, 'XColor', cols(1,:), 'YColor', cols(1,:));
% Label these axes.
xlabel('Orbit - x', labFmt{:});
ylabel('Orbit - y', labFmt{:});
% NB We don't give a title to this plot, because it would collide with the
% the xlabel for the second set of axes (see below).
% Set up the second set of axes and plot the second curve.
ax2 = axes('Position', get(ax1,'Position'), ...
'XAxisLocation', 'top', 'YAxisLocation', 'right', ...
'Color','none', 'XColor',cols(2,:), 'YColor', cols(2,:), ...
'XLim', [-0.25 0.06], 'YLim', [-0.1 0.1], 'FontSize', 13);
hline2 = line(x2, y2, 'Color', cols(2,:), 'Parent', ax2);
% Label these axes.
xlabel('x Deviation from True Ellipse', labFmt{:});
ylabel('y Deviation from True Ellipse', labFmt{:});
% Add a legend, specifying the lines explicitly.
legend([hline1, hline2],'Orbit','Deviation','Location','Best');
% Set some features of the two lines.
set(hline1, 'Linewidth', 0.25, 'Marker', '+', 'Line', '-');
set(hline2, 'Linewidth', 0.25, 'Marker', 'x', 'Line', '--');
```
```
nag_ode_ivp_rk_errass example program results

Calculation with tol = 1.0e-06

t         y1        y2        y3        y4
0.000    0.3000    0.0000    0.0000    2.3805
9.425   -1.7000    0.0000   -0.0000   -0.4201

Componentwise error assessment:
3.81e-06  7.10e-06  6.92e-06  2.10e-06

Worst global error observed was  3.43e-05 - it occurred at T =  6.302

Cost of the integration in evaluations of F is 1361

```
```function d02pz_example
% Initialize variables and arrays.
neq = 4;
lenwrk = 32*neq;
method = 3;
ecc = 0.7;

tstart = 0.0;
ystart = [1.0-ecc; 0.0; 0.0; sqrt((1.0+ecc)/(1.0-ecc))];
tend = 3.0*pi;
thres = [1e-10; 1e-10; 1e-10; 1e-10];
errass = true;
hstart = 0.0;
tol = 1.0e-6;

fprintf('d02pz example program results \n\n');

% We run through the calculation twice: once to output the results at
% a single point, and again to accumulate a series of results for plotting.
nstep = [1; 90];
tend = [3.0*pi; 2.0*pi];

% Prepare to accumulate results.  The first and last points should be the
% same - i.e. so the plot shows a closed trajectory.
xarray = zeros(nstep(2)+1, 1);
yarray = zeros(nstep(2)+1, 4);

for icalc = 1:2
tinc  = tend(icalc)/nstep(icalc);

if icalc == 1
% Output initial results.
fprintf('Calculation with tol = %1.1e\n\n',tol);
fprintf('   t         y1        y2        y3        y4\n');
fprintf(' %6.3f', tstart);
for ieq = 1:neq
fprintf('  %8.4f', ystart(ieq));
end
fprintf('\n');
else
xarray(1) = tstart;
for ieq = 1:neq
yarray(1, ieq) = ystart(ieq);
end
end

for istep = 1:nstep(icalc)
twant = istep*tinc;
% d02pv is a setup routine to be called prior to d02pc.
[work, ifail] = d02pv(tstart, ystart, twant, tol, thres, ...
int64(method), task, errass, int64(lenwrk), 'neq', ...
int64(neq), 'hstart', hstart);
if ifail ~= 0
% Unsuccessful call.  Print message and exit.
error('Warning: d02pv returned with ifail = %1d ',ifail);
end

% Initialize ygot and ymax.  These values don't matter for the
% first call of d02pc, but they mustn't be changed in between
% calls for the same problem.
ygot = ystart;
ymax = ystart;

% In this demo, we disregard warnings about inefficiency from
% d02pc (i.e. ifail = 2,3 or 4 - see documentation) and keep
% calling the routine until the end of the range is reached.
ifail = 2;
while ifail >= 2 && ifail <= 4
[tgot, ygot, ypgot, ymax, work, ifail] = d02pc(@f, ...
int64(neq), twant, ygot, ymax, work);
% Check for other failures.
if ifail == 1 || ifail > 4
% Unsuccessful call.  Print message and exit.
error('Warning: d02pc returned with ifail = %1d ',...
ifail);
end
end

% Store the current result.
if icalc == 2
xarray(istep+1) = tgot;
for ieq = 1:neq
yarray(istep+1, ieq) = ygot(ieq);
end
end
end

% Output final results.
if icalc == 1
fprintf(' %6.3f', tgot);
for ieq = 1:neq
fprintf('  %8.4f', ygot(ieq));
end
fprintf('\n');

% d02pz provides details about global error assessment computed
% during integration with d02pc (or d02pd).
[rmserr, errmax, terrmx, ifail] = d02pz(int64(neq), work);
fprintf('\nComponentwise error assessment:\n        ');
for ieq = 1:neq
fprintf(' %9.2e', rmserr(ieq));
end
fprintf('\n');
fprintf(['\nWorst global error observed was %9.2e', ...
' - it occurred at T = %6.3f\n'], errmax, terrmx);

% d02py is a diagnostic routine.
[totfcn, stpcst, waste, stpsok, hnext, ifail] = d02py;
fprintf(['\nCost of the integration in evaluations of ', ...
'F is %1.0f\n\n\n'], totfcn);
end
end

% Use the first two components of the solution, and calculate the deviation
% from a true ellipse.
x = yarray(:,1);
y = yarray(:,2);
xdev = zeros(nstep(2)+1, 1);
ydev = zeros(nstep(2)+1, 1);
for i = 1:nstep(2)+1
fac = abs((x(i) + ecc)*(x(i) + ecc) + y(i)*y(i)/(ecc*ecc) - 1.0);
xdev(i) = fac*cos(xarray(i));
ydev(i) = fac*sin(xarray(i));
end
% Plot results.
fig = figure('Number', 'off');
display_plot(x, y, xdev, ydev);

function [yp] = f(t, y, yp)
% Evaluate derivative vector.

yp = zeros(4, 1);
r = sqrt((y(1)^2 + y(2)^2));
yp(1) =  y(3);
yp(2) =  y(4);
yp(3) = -y(1)/r^3;
yp(4) = -y(2)/r^3;
function display_plot(x1, y1, x2, y2)
% Formatting for title and axis labels.
titleFmt = {'FontName', 'Helvetica', 'FontWeight', 'Bold', 'FontSize', 14};
labFmt = {'FontName', 'Helvetica', 'FontWeight', 'Bold', 'FontSize', 13};
set(gca, 'FontSize', 13); % for legend, axis tick labels, etc.
% Plot the results.  First, get the list of default colours (we have to
% specify the plot colours by hand).
cols = get(gca, 'ColorOrder');
% Plot the first curve.
hline1 = line(x1, y1, 'Color', cols(1,:));
ax1 = gca;
set(ax1, 'XColor', cols(1,:), 'YColor', cols(1,:));
% Label these axes.
xlabel('Orbit - x', labFmt{:});
ylabel('Orbit - y', labFmt{:});
% NB We don't give a title to this plot, because it would collide with the
% the xlabel for the second set of axes (see below).
% Set up the second set of axes and plot the second curve.
ax2 = axes('Position', get(ax1,'Position'), ...
'XAxisLocation', 'top', 'YAxisLocation', 'right', ...
'Color','none', 'XColor',cols(2,:), 'YColor', cols(2,:), ...
'XLim', [-0.25 0.06], 'YLim', [-0.1 0.1], 'FontSize', 13);
hline2 = line(x2, y2, 'Color', cols(2,:), 'Parent', ax2);
% Label these axes.
xlabel('x Deviation from True Ellipse', labFmt{:});
ylabel('y Deviation from True Ellipse', labFmt{:});
% Add a legend, specifying the lines explicitly.
legend([hline1, hline2],'Orbit','Deviation','Location','Best');
% Set some features of the two lines.
set(hline1, 'Linewidth', 0.25, 'Marker', '+', 'Line', '-');
set(hline2, 'Linewidth', 0.25, 'Marker', 'x', 'Line', '--');
```
```
d02pz example program results

Calculation with tol = 1.0e-06

t         y1        y2        y3        y4
0.000    0.3000    0.0000    0.0000    2.3805
9.425   -1.7000    0.0000   -0.0000   -0.4201

Componentwise error assessment:
3.81e-06  7.10e-06  6.92e-06  2.10e-06

Worst global error observed was  3.43e-05 - it occurred at T =  6.302

Cost of the integration in evaluations of F is 1361

```