using System; using System.Text; using System.Runtime.InteropServices; using NagLibrary; class NagE02Functions { static void Main(string[] args) { const int NE_NOERROR = 0; int m = 14; int ncap = 5; int ncap7 = ncap + 7; double[] lamdadata ={ 1.50, 2.60, 4.00, 8.00 }; double[] x = { 0.20, 0.47, 0.74, 1.09, 1.60, 1.90, 2.60, 3.10, 4.00, 5.15, 6.17, 8.00, 10.00, 12.00 }; double[] y = { 0.00, 2.00, 4.00, 6.00, 8.00, 8.62, 9.10, 8.90, 8.15, 7.00, 6.00, 4.54, 3.39, 2.56 }; double[] w = { 0.20, 0.20, 0.30, 0.70, 0.90, 1.00, 1.00, 1.00, 0.80, 0.50, 0.70, 1.00, 1.00, 1.00 }; double[] lamda = new double[ncap7]; double[] c = new double[ncap7]; double ss = 0.0; double fit = 0.0; double xarg = 0.0; nag_declarations.Nag_Spline spline = new nag_declarations.Nag_Spline(); nag_declarations.NagError fail = new nag_declarations.NagError(); fail.message = new byte[512]; Encoding enc = Encoding.ASCII; for (int i = 4, j = 0; i < ncap + 3; i++, j++) { lamda[i] = lamdadata[j]; } spline.n = ncap7; spline.lamda = Marshal.AllocHGlobal(ncap7 * sizeof(double)); Marshal.Copy(lamda, 0, spline.lamda, ncap7); /* nag_1d_spline_fit_knots (e02bac). * Least-squares curve cubic spline fit (including * interpolation), one variable */ nag_declarations.e02bac(m, x, y, w, ref ss, ref spline, ref fail); if (fail.code != NE_NOERROR) { Console.WriteLine("Error from nag_1d_spline_fit_knots (e02bac):"); Console.WriteLine(enc.GetString(fail.message)); goto End; } Marshal.Copy(spline.lamda, lamda, 0, ncap7); Marshal.Copy(spline.c, c, 0, ncap7); Console.Write("\nNumber of distinct knots = {0}\n\n", ncap + 1); Console.Write("Distinct knots located at \n\n"); for (int j = 3; j < ncap + 4; j++) Console.Write("{0, 8:f4}{1}", lamda[j], (j - 3) % 6 == 5 || j == ncap + 3 ? "\n" : " "); Console.Write("\n\n J B-spline coeff c\n\n"); for (int j = 0; j < ncap + 3; ++j) Console.Write(" {0} {1,13:f4}\n", j + 1, c[j]); Console.Write("\nResidual sum of squares = "); Console.Write("{0, 11:e2}\n\n", ss); Console.Write("Cubic spline approximation and residuals\n"); Console.Write(" r Abscissa Weight Ordinate Spline Residual\n\n"); for (int r = 0; r < m; ++r) { /* nag_1d_spline_evaluate (e02bbc). * Evaluation of fitted cubic spline, function only */ nag_declarations.e02bbc(x[r], ref fit, ref spline, ref fail); if (fail.code != NE_NOERROR) { Console.WriteLine("Error from nag_1d_spline_evaluate (e02bbc):"); Console.WriteLine(enc.GetString(fail.message)); goto End; } Console.Write("{0, 3} {1, 11:f4} {2, 11:f4} {3, 11:f4} {4, 11:f4} {5, 10:e1}\n", r + 1, x[r], w[r], y[r], fit, fit - y[r]); if (r < m - 1) { xarg = (x[r] + x[r + 1]) * 0.5; /* nag_1d_spline_evaluate (e02bbc), see above. */ nag_declarations.e02bbc(xarg, ref fit, ref spline, ref fail); if (fail.code != NE_NOERROR) { Console.WriteLine("Error from nag_1d_spline_evaluate (e02bbc):"); Console.WriteLine(enc.GetString(fail.message)); goto End; } Console.Write(" {0,14:f4} {1, 33:f4}\n", xarg, fit); } } End: Marshal.FreeHGlobal(spline.lamda); } }