using System; using System.Text; using System.Runtime.InteropServices; using NagLibrary; public class NagE04Functions { public static void Main() { nag_declarations.nag_opt_simplex_easy_funct_DELEGATE F = new nag_declarations.nag_opt_simplex_easy_funct_DELEGATE(funct); nag_declarations.nag_opt_simplex_easy_monit_DELEGATE mon = new nag_declarations.nag_opt_simplex_easy_monit_DELEGATE(monit); int i; int n = 2; double[] x = new double[2]; x[0] = -1.0; x[1] = 1.0; double fmin = 0.0; double tolf, tolx; int maxcal = 100; int monitoring; nag_declarations.Nag_Comm user_comm = new nag_declarations.Nag_Comm(); nag_declarations.NagError fail = new nag_declarations.NagError(); fail.message = new byte[512]; Encoding enc = Encoding.ASCII; /* Set monitoring to a nonzero value to obtain monitoring information */ monitoring = 0; user_comm.p = Marshal.AllocHGlobal(sizeof(int)); Marshal.WriteInt32(user_comm.p, monitoring); tolf = Math.Sqrt(nag_declarations.nag_machine_precision()); tolx = Math.Sqrt(tolf); /* nag_opt_simplex_easy (e04cbc). * Finds an approximation to a minimum of a function of n variables. */ nag_declarations.nag_opt_simplex_easy(n, x, ref fmin, tolf, tolx, F, mon, maxcal, ref user_comm, ref fail); if (fail.code == 0) { Console.WriteLine("The final function value is {0, 12:f4}\n", fmin); Console.WriteLine("at the point"); for (i = 0; i < n; ++i) { Console.WriteLine(" {0, 12:f4}", x[i]); } } else { Console.WriteLine("Error from nag_opt_simplex_easy (e04cbc):"); Console.WriteLine(enc.GetString(fail.message)); } Marshal.FreeHGlobal(user_comm.p); } public static void funct(int n, IntPtr xc_ptr, ref double objf, ref nag_declarations.Nag_Comm comm) { double[] xc = new double[n]; Marshal.Copy(xc_ptr, xc, 0, n); objf = Math.Exp(xc[0]) * (xc[0] * 4.0 * (xc[0] + xc[1]) + xc[1] * 2.0 * (xc[1] + 1.0) + 1.0); } public static void monit(double fmin, double fmax, IntPtr sim_ptr, int n, int ncall, double serror, double vratio, ref nag_declarations.Nag_Comm comm) { int i, j; int monitoring = Marshal.ReadInt32(comm.p); double[] sim = new double[(n + 1) * n]; Marshal.Copy(sim_ptr, sim, 0, (n + 1) * n); if (monitoring != 0) { Console.WriteLine("\nThere have been {0} function calls\n", ncall); Console.WriteLine("The smallest function value is {0, 10:f4}\n", fmin); Console.WriteLine("\nThe simplex is\n"); for (i = 0; i < n + 1; ++i) { for (j = 0; j < n; ++j) { Console.WriteLine(" {0, 13:f4}", sim[j * (n + 1) + i]); } Console.WriteLine("\n"); } Console.WriteLine("\nThe standard deviation in function values at the vertices of the simplex is {0, 10:f4}\n", serror); Console.WriteLine("The linearized volume ratio of the current simplex to the starting one is {0, 10:f4}\n", vratio); } } }