-
Notifications
You must be signed in to change notification settings - Fork 193
Numerical Efficiency #4802
Description
Is it worth to write down rules for increasing efficiency of algorithms (not only in Modelica.Math), or should we rely on AI?
I have an example - which implementation is more efficient and why?
Asking especially colleagues involved in such questions at the tool vendors: @casella @HansOlsson @maltelenz
(I have tested: The alternative implementation is more efficient)
function quadratureNewtonCotes "Quadrature using Newton-Cotes formulas"
extends Modelica.Icons.Function;
input Modelica.Math.Nonlinear.Interfaces.partialScalarFunction f "Integrand function";
input Real a "Lower limit of integration interval";
input Real b "Upper limit of integration interval";
input Integer N = 360 "Number of intervals";
input Integer d(final min=1, final max=6) = 1 "Degree of interpolation polynominal";
output Real integral "Integral value";
protected
constant Real c[6,7]={
{ 1, 1, 0, 0, 0, 0, 0},
{ 1, 4, 1, 0, 0, 0, 0},
{ 1, 3, 3, 1, 0, 0, 0},
{ 7, 32, 12, 32, 7, 0, 0},
{19, 75, 50, 50, 75, 19, 0},
{41,216, 27,272, 27,216,41}} "Weights";
Real cRow[d + 1]=c[d,1:d + 1];
Integer n=N + mod(-N, d) "Ensure number of intervals is a multiple of d";
Real h=(b - a)/n "Width of intervals";
Real x[n + 1]=linspace(a, b, n + 1) "Knots";
Real y[n + 1] "Function evaluation at interval borders";
algorithm
y:={f(x[k]) for k in 1:n + 1};
integral:=sum({sum(cRow.*y[kp + 1 - d:kp + 1]) for kp in d:d:n})*h*d/sum(cRow);
// alternative implementation:
/*
integral:=0;
for kp in d:d:n loop
integral:=integral + sum(cRow[k]*y[kp - d + k] for k in 1:d + 1);
end for;
integral:=integral*h*d/sum(cRow);
*/
end quadratureNewtonCotes;