Listing 3: C# code that uses the assembly naglib in a C# console application.
using System;
using System.Runtime.InteropServices;
using NAGLIB;
namespace USE_NAGLIBS
{
class DCLASS : NAG_FUNCTIONS
{
public unsafe void objfun (Int32 n, Double *x,
Double *objf, Double *g, Int32 comm)
{
Double ex1, x1, x2;
ex1 = Math.Exp(x[0]);
x1 = x[0];
x2 = x[1];
*objf = ex1*(4.0*x1*x1 + 2.0*x2*x2 + 4.0*x1*x2 + 2.0*x2 + 1.0);
g[0] = 4.0*ex1*(2.0*x1 + x2) + *objf;
g[1] = 2.0*ex1*(2.0*x2+2.0*x1 + 1.0);
}
public Double the_integrand_c(Double x)
{
Double pi = Math.PI;
Double val;
val = (x*Math.Sin(x*30.0)/1.0-x*x/(pi*pi*4.0));
return val;
}
}
class RUNIT
{
static unsafe void Main(string[] args)
{
Int32 tda = 4, n = 4, n2 = 2, j, flag = 0;
Double [] r = new Double [30];
Double [] x2 = new Double [2];
Double [] g = new Double [2];
Double a1, b1, objf = 0.0, abserr = 0.0, the_answer, x;
Double [,] a = new Double[n,n];
DCLASS tt = new DCLASS();
x = -1.0;
the_answer = tt.CUM_NORM(x);
Console.WriteLine ("The value of the cumulative normal = {0,8:F4}", the_answer);
INTEGRAND_FUN_TYPE myfun_c=new INTEGRAND_FUN_TYPE (tt.the_integrand_c);
OBJ_FUN_TYPE myobjfun = new OBJ_FUN_TYPE (tt.objfun);
a1 = 0.0;
b1 = Math.PI*2.0;
flag = 0;
the_answer = 0.0;
tt.QUADRATURE(a1, b1, ref the_answer, ref abserr, ref flag, myfun_c);
Console.WriteLine("The integral (default maximum number of
subintervals) = {0,8:F6} ",the_answer);
flag = 0;
tt.QUADRATURE_max_subint = 3;
tt.QUADRATURE(a1, b1, ref the_answer, ref abserr, ref flag, myfun_c);
Console.WriteLine("The integral (maximum number of
subintervals set to 3) = {0,8:F6} ",the_answer);
x2[0] = -1.0;
x2[1] = 1.0;
n2 = 2;
flag = 0;
tt.OPTIMIZE(n2, ref x2[0], ref g[0], ref objf, ref flag, myobjfun);
Console.Write("The optimization solution vector is :");
for (j = 0; j < 2; ++j) {
Console.Write("{0,8:F4}",x2[j]);
}
Console.WriteLine();
Console.WriteLine("The value of the objective function is: {0,8:E4}",objf);
flag = 0;
// first row
a[0,0] = 0.5;
a[0,1] = 0.0;
a[0,2] = 2.3;
a[0,3] = -2.6;
// second row
a[1,0] = 0.0;
a[1,1] = 0.5;
a[1,2] = -1.4;
a[1,3] = -0.7;
// third row
a[2,0] = 2.3;
a[2,1] = -1.4;
a[2,2] = 0.5;
a[2,3] = 0.0;
// fourth row
a[3,0] = -2.6;
a[3,1] = -0.7;
a[3,2] = 0.0;
a[3,3] = 0.5;
tt.REAL_SYMM_EIGEN(n, ref a[0,0], tda, ref r[0], ref flag);
Console.Write("The Eigenvalues are:");
for (j = 0; j <= 3; ++j) {
Console.Write("{0,8:F4}", r[j]);
}
Console.WriteLine();
}
}
}