Exemplo n.º 1
0
        static public Pair <double[], int[]> SimplifiedMethod(double a, double b,
                                                              ScalarFunk1 funk, ScalarFunk1 funkDerivative, double Eps = 10e-4)
        {
            double countArea    = 10;
            var    localization = Localization(a, b, funk, countArea);
            var    leftBorders  = localization.FirstElement;
            var    rightBorders = localization.SecondElement;

            var results = new double[leftBorders.Length];
            var iters   = new int[leftBorders.Length];

            for (int i = 0; i < results.Length; i++)
            {
                int    countIter = 0;
                double xCurrent;
                double xNext = (rightBorders[i] + leftBorders[i]) / 2;
                double staticFunkDerivative = funkDerivative(xNext);
                do
                {
                    countIter++;
                    xCurrent = xNext;
                    xNext    = xCurrent - (funk(xCurrent) / staticFunkDerivative);
                } while (Math.Abs(xNext - xCurrent) > Eps);
                iters[i]   = countIter;
                results[i] = xNext;
            }
            return(new Pair <double[], int[]> {
                FirstElement = results, SecondElement = iters
            });
        }
Exemplo n.º 2
0
        static private Pair <double[], double[]> Localization(double a, double b, ScalarFunk1 funk, double countArea = 10)
        {
            var    leftBorders     = new List <double>();
            var    rightBorders    = new List <double>();
            double step            = (b - a) / countArea;
            double tempLeftBorder  = a;
            double tempRightBorder = a + step;

            for (int i = 0; i < countArea - 1; i++)
            {
                if (funk(tempLeftBorder) * funk(tempRightBorder) < 0)
                {
                    leftBorders.Add(tempLeftBorder);
                    rightBorders.Add(tempRightBorder);
                }
                tempLeftBorder   = tempRightBorder;
                tempRightBorder += step;
            }

            return(new Pair <double[], double[]>
            {
                FirstElement = leftBorders.ToArray(),
                SecondElement = rightBorders.ToArray()
            });
        }
Exemplo n.º 3
0
        //Модифицированный
        static public Pair <double[], int[]> DifferenceMethod(double a, double b,
                                                              ScalarFunk1 funk, double Eps = 10e-4)
        {
            double countArea    = 10;
            var    localization = Localization(a, b, funk, countArea);
            var    leftBorders  = localization.FirstElement;
            var    rightBorders = localization.SecondElement;

            var results = new double[leftBorders.Length];
            var iters   = new int[leftBorders.Length];

            //Малая велечина по X
            double h = 10e-2;

            for (int i = 0; i < results.Length; i++)
            {
                int    countIter = 0;
                double xCurrent;
                double xNext = (rightBorders[i] + leftBorders[i]) / 2;
                do
                {
                    countIter++;
                    xCurrent = xNext;
                    xNext    = xCurrent - h * (funk(xCurrent) / (funk(xCurrent + h) - funk(xCurrent)));
                } while (Math.Abs(xNext - xCurrent) > Eps);
                iters[i]   = countIter;
                results[i] = xNext;
            }
            return(new Pair <double[], int[]> {
                FirstElement = results, SecondElement = iters
            });
        }
Exemplo n.º 4
0
        static public double AnalysisMethod(TypeKF typeKF, ScalarFunk1 f, double defA, double a, double b, double alpha, int n, double Eps)
        {
            double L       = 2;
            Vector vectorH = new Vector(3);

            vectorH.data[1] = b - a;
            vectorH.data[2] = (b - a) / L;

            int countIter = 1;

            double result = 0.0;

            double tempR = Double.PositiveInfinity;

            do
            {
                countIter++;
                vectorH.data[0] = vectorH.data[1];
                vectorH.data[1] = vectorH.data[2];
                vectorH.data[2] = vectorH.data[1] / L;
                //Эйткен
                Vector vectorS = new Vector(3);
                vectorS.data[0] = SKF(typeKF, f, defA, a, b, alpha, n, vectorH.data[0]);
                vectorS.data[1] = SKF(typeKF, f, defA, a, b, alpha, n, vectorH.data[1]);
                vectorS.data[2] = SKF(typeKF, f, defA, a, b, alpha, n, vectorH.data[2]);

                double m = -Math.Log((Math.Abs(vectorS.data[2] - vectorS.data[1])) / (Math.Abs(vectorS.data[1] - vectorS.data[0]))) / Math.Log(L);

                //Рижардсон

                Matrix matrix_Cs_J = new Matrix(3);
                for (int i = 0; i < matrix_Cs_J.N; i++)
                {
                    for (int j = 0; j < matrix_Cs_J.N - 1; j++)
                    {
                        matrix_Cs_J.data[i][j] = Math.Pow(vectorH.data[i], m + j);
                    }
                    matrix_Cs_J.data[i][matrix_Cs_J.N - 1] = -1;
                }

                Matrix matrix_Cs_J_L = new Matrix(n);
                Matrix matrix_Cs_J_U = new Matrix(n);
                Matrix matrix_Cs_J_P = new Matrix(n);
                LUP_decomposition.LUP(matrix_Cs_J, matrix_Cs_J_L, matrix_Cs_J_U, matrix_Cs_J_P);

                Vector vector_Cs_J = LUP_decomposition.SLAU(matrix_Cs_J_L, matrix_Cs_J_U, matrix_Cs_J_P, -1 * vectorS);

                result = vector_Cs_J.data[2];
                tempR  = vectorS.data[2] - result;
            } while (Math.Abs(tempR) > Eps);
            Console.WriteLine($"Count iter: {Math.Pow(L, countIter)}");
            return(result);
        }
Exemplo n.º 5
0
        static public double MiddleRectangleRule(ScalarFunk1 F, double a, double b, int n)
        {
            double result = 0.0;

            double h = (b - a) / n;

            for (int i = 1; i <= n; i++)
            {
                result += F(a + (i - 1 / 2) * h);
            }
            result *= h;
            return(result);
        }
Exemplo n.º 6
0
        static public double SKF(TypeKF typeKF, ScalarFunk1 f, double defA, double a, double b, double alpha, int n, double h)
        {
            int    k      = (Int32)((b - a) / h);
            double result = 0.0;

            for (int i = 0; i < k; i++)
            {
                switch (typeKF)
                {
                case TypeKF.NewtonCots:
                    result += IKF_NewtonCots(f, defA, a + i * h, a + (i + 1) * h, alpha, n);
                    break;

                case TypeKF.Gauss:
                    result += KF_Gauss(f, defA, a + i * h, a + (i + 1) * h, alpha, n);
                    break;
                }
            }

            return(result);
        }
Exemplo n.º 7
0
        static public double IKF_NewtonCots(ScalarFunk1 f, double defA, double a, double b, double alpha, int n)
        {
            //Получаем вектор узлов
            Vector vectorX = new Vector(n);
            double step    = (b - a) / (n - 1);

            for (int i = 0; i < n; i++)
            {
                vectorX.data[i] = a + i * step;
            }

            //Вычисляем моменты от 0 до n - 1
            Vector vectorMoments = new Vector(n);

            for (int i = 0; i < n; i++)
            {
                vectorMoments.data[i] = CountMoment(defA, a, b, alpha, i);
            }

            //Решаем СЛАУ и находим Aj
            Matrix matrixX = new Matrix(n);

            FillMatrixX(matrixX, vectorX);
            Matrix matrixX_L = new Matrix(n);
            Matrix matrixX_U = new Matrix(n);
            Matrix matrixX_P = new Matrix(n);

            LUP_decomposition.LUP(matrixX, matrixX_L, matrixX_U, matrixX_P);
            Vector vectorA = LUP_decomposition.SLAU(matrixX_L, matrixX_U, matrixX_P, vectorMoments);

            //Получем ответ по КФ
            double result = 0.0;

            for (int i = 0; i < n; i++)
            {
                result += vectorA.data[i] * f(vectorX.data[i]);
            }

            return(result);
        }
Exemplo n.º 8
0
        static void Main(string[] args)
        {
            #region Условия
            double c2 = 0.05;

            double x0 = 0;
            double xN = 5;

            double A = 3;
            double B = 3;
            double C = -3;

            var Y0 = new double[4] {
                1, 1, A, 1
            };

            VectorFunk f = (double X, double[] Y) =>
            {
                var resultY = new double[Y.Length];
                resultY[0] = 2 * X * Math.Pow(Math.Abs(Y[1]), 1.0 / B) * Math.Sign(Y[1]) * Y[3];
                resultY[1] = 2 * B * X * Math.Exp((B / C) * (Y[2] - A)) * Y[3];
                resultY[2] = 2 * C * X * Y[3];
                resultY[3] = -2 * X * Math.Log(Math.Abs(Y[0]));

                return(resultY);
            };

            var realFuncs = new ScalarFunk1[4];
            realFuncs[0] = (double X) => Math.Exp(Math.Sin(X * X));
            realFuncs[1] = (double X) => Math.Exp(B * Math.Sin(X * X));
            realFuncs[2] = (double X) => C *Math.Sin(X *X) + A;

            realFuncs[3] = (double X) => Math.Cos(X * X);
            #endregion
            VectorFunk1 valueInRealFunc = (double X) => new double[] { realFuncs[0](X), realFuncs[1](X), realFuncs[2](X), realFuncs[3](X) };

            //Создание методов
            int p_C2           = 2;
            int p_MP           = 2;
            var methodC2_rk    = OduCalculation.CreateMethod_byC2_P2S2(c2, f);
            var middlePoint_rk = OduCalculation.GetMethod_MiddlePoint_P2S2(f);


            #region Запуск на константном шаге
            int    k_const = 9;
            double h_const = 1 / Math.Pow(2, k_const);
            var    result_methodC2_ConstH = OduCalculation.Result_ConstH(x0, xN, Y0, methodC2_rk, h_const);
            var    result_methodMP_ConstH = OduCalculation.Result_ConstH(x0, xN, Y0, middlePoint_rk, h_const);

            //ExcelTool.GetInstance().Export_points_4Func("MethodC2_ConstH", result_methodC2_ConstH, valueInRealFunc);
            //ExcelTool.GetInstance().Export_points_4Func("MethodMP_ConstH", result_methodMP_ConstH, valueInRealFunc);
            #endregion

            #region Принт точек
            //for (int i = 0; i < result_methodC2.Length; i++)
            //{
            //	string tempPoint = $"({x0 + i * h}".Replace(',', '.') + ", " + $"{result_methodC2[i].data[0]})".Replace(',', '.');
            //	Console.Write($"{tempPoint}, ");
            //}
            #endregion

            #region Все итерации
            //Console.Write("\nx: ");
            //for (int i = 0; i < 4; i++)
            //{
            //	Console.Write($" y{i}");
            //}
            //Console.WriteLine("\nResult methodC2:");
            //for (int i = 0; i < result_methodC2.Length; i++)
            //{
            //	Console.Write($"\n{i} ({x0 + i * h}): ");
            //	result_methodC2[i].Show();
            //}
            #endregion


            #region Сравнение с реальным значением
            Console.WriteLine("\nDifferent methodC2 with real in last point:");
            (new Vector(valueInRealFunc(result_methodC2_ConstH.Last().FirstElement)) - result_methodC2_ConstH.Last().SecondElement).Show();
            Console.WriteLine("\nDifferent methodMP with real in last point:");
            (new Vector(valueInRealFunc(result_methodMP_ConstH.Last().FirstElement)) - result_methodMP_ConstH.Last().SecondElement).Show();
            #endregion

            #region Для графика зависимости нормы от длины шага
            int k_end       = 7;
            var Rs_methodC2 = OduCalculation.GetRs(x0, xN, Y0, methodC2_rk, k_end, p_C2);
            Console.WriteLine("\nRs methodC2: ");
            Rs_methodC2.Show1();
            var Rs_MiddlePoint = OduCalculation.GetRs(x0, xN, Y0, middlePoint_rk, k_end, p_MP);
            Console.WriteLine("Rs middlePoint: ");
            Rs_MiddlePoint.Show1();
            #endregion

            #region Нахождение h_opt по Рунге
            var tol      = 10e-5;
            var h_opt_c2 = OduCalculation.H_Opt(x0, xN, Y0, methodC2_rk, p_C2, tol);
            Console.Write($"\nh_opt_c2: {h_opt_c2}");
            var h_opt_mp = OduCalculation.H_Opt(x0, xN, Y0, middlePoint_rk, p_MP, tol);
            Console.Write($"\nh_opt_mp: {h_opt_mp}");

            var result_methodC2_check = OduCalculation.Result_ConstH(x0, xN, Y0, methodC2_rk, h_opt_c2);
            var R_methodC2_check      = (new Vector(valueInRealFunc(result_methodC2_check.Last().FirstElement)) - result_methodC2_check.Last().SecondElement).Norm();
            Console.WriteLine($"\nCheck R methodC2 with h_opt: {R_methodC2_check}");

            var result_methodMP_check = OduCalculation.Result_ConstH(x0, xN, Y0, methodC2_rk, h_opt_c2);
            var R_methodMP_check      = (new Vector(valueInRealFunc(result_methodMP_check.Last().FirstElement)) - result_methodMP_check.Last().SecondElement).Norm();
            Console.WriteLine($"Check R methodMP with h_opt: {R_methodMP_check}");

            var realRsOnX_methodC2_h_opt = OduCalculation.RealRsOnX(result_methodC2_check, valueInRealFunc);
            var realRsOnX_methodMP_h_opt = OduCalculation.RealRsOnX(result_methodMP_check, valueInRealFunc);

            //ExcelTool.GetInstance().Export_RealRsOnX("RsOnX_methodC2_hOpt", realRsOnX_methodC2_h_opt);
            //ExcelTool.GetInstance().Export_RealRsOnX("RsOnX_methodMP_hOpt", realRsOnX_methodMP_h_opt);
            #endregion

            #region Запуск на вариативном шаге
            var h_begin = 1 / Math.Pow(2, 6);
            //Выбор начального шага
            var result0 = new Vector(f(x0, Y0));
            var delta   = Math.Pow(1 / Math.Max(Math.Abs(x0), Math.Abs(xN)), p_C2 + 1) + Math.Pow(result0.Norm(), p_C2 + 1);
            //h_begin = Math.Pow(1e-5 / delta, 1.0 / (p_C2 + 1));

            var accH_methodC2        = new List <Pair <double, Pair <double, List <double> > > >();
            var result_methodC2_varH = OduCalculation.Result_VariableH(x0, xN, Y0, methodC2_rk, p_C2, h_begin, ref accH_methodC2);
            Console.WriteLine("\nDifferent methodC2 with real in last point:");
            (new Vector(valueInRealFunc(result_methodC2_varH.Last().FirstElement)) - result_methodC2_varH.Last().SecondElement).Show();

            var accH_methodMP        = new List <Pair <double, Pair <double, List <double> > > >();
            var result_methodMP_varH = OduCalculation.Result_VariableH(x0, xN, Y0, middlePoint_rk, p_C2, h_begin, ref accH_methodMP);
            Console.WriteLine("\nDifferent methodMP with real in last point:");
            (new Vector(valueInRealFunc(result_methodMP_varH.Last().FirstElement)) - result_methodMP_varH.Last().SecondElement).Show();

            //ExcelTool.GetInstance().Export_InfoHs("MethodC2_InfoHs", accH_methodC2);
            //ExcelTool.GetInstance().Export_InfoHs("MethodMP_InfoHs", accH_methodMP);

            //ExcelTool.GetInstance().Export_points_4Func("MethodC2_VarH", result_methodC2_varH, valueInRealFunc);
            //ExcelTool.GetInstance().Export_points_4Func("MethodMP_VarH", result_methodMP_varH, valueInRealFunc);

            var realRsOnX_methodC2_h_var = OduCalculation.RealRsOnX(result_methodC2_varH, valueInRealFunc);
            var realRsOnX_methodMP_h_var = OduCalculation.RealRsOnX(result_methodMP_varH, valueInRealFunc);

            //ExcelTool.GetInstance().Export_RealRsOnX("RsOnX_methodC2_hVar", realRsOnX_methodC2_h_var);
            //ExcelTool.GetInstance().Export_RealRsOnX("RsOnX_methodMP_hVar", realRsOnX_methodMP_h_var);

            var countCallF_onRtol_methodC2 = OduCalculation.CountCallF_onRtol(x0, xN, Y0, methodC2_rk, p_C2, 2);
            var countCallF_onRtol_methodMP = OduCalculation.CountCallF_onRtol(x0, xN, Y0, middlePoint_rk, p_C2, 2);

            //ExcelTool.GetInstance().Export_CountCallF("CountCallF_methodC2", countCallF_onRtol_methodC2);
            //ExcelTool.GetInstance().Export_CountCallF("CountCallF_methodMP", countCallF_onRtol_methodMP);
            #endregion
        }
Exemplo n.º 9
0
        static void Task_4()
        {
            //Вариант 13
            double      alpha = 0.2;
            double      a     = 1.5;
            double      b     = 2.3;
            double      defA  = a;
            ScalarFunk1 f     = (double X) => 2 * Math.Cos(3.5 * X) * Math.Exp(5 * X / 3) + 3 * Math.Sin(1.5 * X) * Math.Exp(-4 * X) + 3;
            ScalarFunk1 p     = (double X) => 1 / Math.Pow(X - a, alpha);

            ScalarFunk1 F = (double X) => f(X) * p(X);

            int    countNode_MRR = 1000;
            double result_MRR    = IntegralCalculation.MiddleRectangleRule(F, a, b, countNode_MRR);

            Console.WriteLine($"Result by MiddleRectangleRule (CountNode: {countNode_MRR}): {result_MRR}");


            int    countNode_IKF_NC = 3;
            double result_IKF_NC    = IntegralCalculation.IKF_NewtonCots(f, defA, a, b, alpha, countNode_IKF_NC);

            Console.WriteLine($"\n\nResult by IKF_NewtonCots (CountNode: {countNode_IKF_NC}): {result_IKF_NC}");

            int    countNode_SKF_NC = 3;
            int    countPart_SKF_NC = 3;
            double h_SKF_NC         = (b - a) / countPart_SKF_NC;
            double result_SKF_NC    = IntegralCalculation.SKF(IntegralCalculation.TypeKF.NewtonCots, f, defA, a, b, alpha, countNode_SKF_NC, h_SKF_NC);

            Console.WriteLine($"Result by SKF IKF_NewtonCots (CountNode: {countNode_SKF_NC}; StepH: {h_SKF_NC};): {result_SKF_NC}");

            Console.WriteLine($"\nAnalysisMethod_NewtonCots");
            int    countNode_analys_NC = 3;
            double Eps_analys_NC       = 10e-6;;
            double result_analys_NC    = IntegralCalculation.AnalysisMethod(IntegralCalculation.TypeKF.NewtonCots, f, defA, a, b, alpha, countNode_analys_NC, Eps_analys_NC);

            Console.WriteLine($"Result : {result_analys_NC}");

            Console.WriteLine($"\nAnalysisMethod_Opt_NewtonCots");
            int    countNode_analys_Opt_NC = 3;
            double Eps_analys_Opt_NC       = 10e-6;;
            double result_analys_Opt_NC    = IntegralCalculation.AnalysisMethod_Opt(IntegralCalculation.TypeKF.NewtonCots, f, defA, a, b, alpha, countNode_analys_Opt_NC, Eps_analys_Opt_NC);

            Console.WriteLine($"Result : {result_analys_Opt_NC}");

            Console.WriteLine("___________________________________________________________________________________________");

            int    countNode_KF_G = 3;
            double result_KF_G    = IntegralCalculation.KF_Gauss(f, defA, a, b, alpha, countNode_KF_G);

            Console.WriteLine($"\n\nResult by KF_Gauss (CountNode: {countNode_KF_G}): {result_KF_G}");

            int    countNode_SKF_G = 3;
            int    countPart_SKF_G = 3;
            double h_SKF_G         = (b - a) / countPart_SKF_G;
            double result_SKF_G    = IntegralCalculation.SKF(IntegralCalculation.TypeKF.Gauss, f, defA, a, b, alpha, countNode_SKF_G, h_SKF_G);

            Console.WriteLine($"Result by SKF KF_Gauss (CountNode: {countNode_SKF_G}; StepH: {h_SKF_G};): {result_SKF_G}");


            Console.WriteLine($"\nAnalysisMethod_Gauss");
            int    countNode_analys_G = 3;
            double Eps_analys_G       = 10e-6;;
            double result_analys_G    = IntegralCalculation.AnalysisMethod(IntegralCalculation.TypeKF.Gauss, f, defA, a, b, alpha, countNode_analys_G, Eps_analys_G);

            Console.WriteLine($"Result : {result_analys_G}");

            Console.WriteLine($"\nAnalysisMethod_Opt_Gauss");
            int    countNode_analys_Opt_G = 3;
            double Eps_analys_Opt_G       = 10e-6;;
            double result_analys_Opt_G    = IntegralCalculation.AnalysisMethod_Opt(IntegralCalculation.TypeKF.Gauss, f, defA, a, b, alpha, countNode_analys_Opt_G, Eps_analys_Opt_G);

            Console.WriteLine($"Result : {result_analys_Opt_G}");
        }
Exemplo n.º 10
0
        static void Task_3()
        {
            #region  ешение скалярного уравнения
            Console.WriteLine("ScalarEquation: x - sin(x) = 0.25");
            ScalarFunk1 func1    = (double X) => (X - Math.Sin(X) - 0.25);
            ScalarFunk1 funcDer1 = (double X) => (1 - Math.Cos(X));
            double      a1       = 0.0;
            double      b1       = 17.5;
            Console.WriteLine("Mode: Difference");
            var diff_results1 = MethodNewton_Scalar.DifferenceMethod(a1, b1, func1);
            PrintResult(diff_results1);
            Console.WriteLine("Mode: Simplified");
            var sim_results1 = MethodNewton_Scalar.SimplifiedMethod(a1, b1, func1, funcDer1);
            PrintResult(sim_results1);
            Console.WriteLine("Mode: Defualt");
            var def_results1 = MethodNewton_Scalar.DefualtMethod(a1, b1, func1, funcDer1);
            PrintResult(def_results1);

            Console.WriteLine("\nScalarEquation: x^3 = e^x - 1");
            ScalarFunk1 func2    = (double X) => (Math.Pow(X, 3) - Math.Pow(Math.E, X) + 1);
            ScalarFunk1 funcDer2 = (double X) => (3 * Math.Pow(X, 2) - Math.Pow(Math.E, X));
            double      a2       = -2.0;
            double      b2       = 2.0;
            Console.WriteLine("Mode: Difference");
            var diff_results2 = MethodNewton_Scalar.DifferenceMethod(a2, b2, func2);
            PrintResult(diff_results2);
            Console.WriteLine("Mode: Simplified");
            var sim_results2 = MethodNewton_Scalar.SimplifiedMethod(a2, b2, func2, funcDer2);
            PrintResult(sim_results2);
            Console.WriteLine("Mode: Defualt");
            var def_results2 = MethodNewton_Scalar.DefualtMethod(a2, b2, func2, funcDer2);
            PrintResult(def_results2);
            #endregion

            #region  ешение СНАУ
            Console.WriteLine("\nSNAU________________________________________________");
            //Задаём вектор функций системы
            var vectorFunks = new ScalarFunk1_N[10];
            InitVectorFunks(vectorFunks);

            //Задём матрицу Якоби системы
            var matrixFunks = new ScalarFunk1_N[10][];
            InitMatrixFunks(matrixFunks);

            //Задаём стартовое приближение
            var vectorStart = new Vector(vectorFunks.Length);
            //x5 = -0.5 | -0.2
            vectorStart.SetValues(new double[] { 0.5, 0.5, 1.5, -1.0, -0.2, 1.5, 0.5, -0.5, 1.5, -1.5 });
            Console.Write("Vector start: ");
            vectorStart.Show();

            //Кол-во прераций на LUP и СЛАУ
            var countMathOper_LUP  = (matrixFunks.Length * matrixFunks.Length * (matrixFunks.Length + 1)) / 2;
            var countMathOper_SLAU = matrixFunks.Length * (2 * matrixFunks.Length + 5);

            //Инструмент для подсчёта времени
            var stopWatch = new Stopwatch();

            RunnigStopWatch(stopWatch);
            //Console.WriteLine($"Time: {stopWatch.ElapsedMilliseconds} milliseconds");
            stopWatch.Reset();

            //Чистый дефолтный метод Ньютона
            Console.WriteLine("\nSingle: #Defualt_method");
            var vectorResultDef_pair = MethodNewton_SNAU.Defualt_withSLAU(vectorStart, matrixFunks, vectorFunks, stopWatch);
            Console.WriteLine($"Time: {stopWatch.ElapsedTicks} ticks");
            Console.WriteLine("Count math.operation: " +
                              $"{(countMathOper_LUP + countMathOper_SLAU + 10) * vectorResultDef_pair.SecondElement}");
            Console.WriteLine($"Count iter: {vectorResultDef_pair.SecondElement}");
            Console.Write("Result vector: ");
            vectorResultDef_pair.FirstElement.Show();
            Console.Write("Check vector: ");
            var checkVec_def = new Vector(vectorFunks.Length);
            checkVec_def.SetValueByFunks(vectorFunks, vectorResultDef_pair.FirstElement.data);
            checkVec_def.Show();

            //stopWatch.Reset();

            //Чистый модифицированный метод Ньютона
            Console.WriteLine("\nSingle: #Modified_Method");
            var vectorResultMod_pair = MethodNewton_SNAU.Modified_withSLAU(vectorStart, matrixFunks, vectorFunks, stopWatch);
            Console.WriteLine($"Time: {stopWatch.ElapsedTicks} ticks");
            Console.WriteLine("Count math.operation: " +
                              $"{countMathOper_LUP + (countMathOper_SLAU + 10) * vectorResultMod_pair.SecondElement}");
            Console.WriteLine($"Count iter: {vectorResultMod_pair.SecondElement}");
            Console.Write("Result vector: ");
            vectorResultMod_pair.FirstElement.Show();
            Console.Write("Check vector: ");
            var checkVec_mod = new Vector(vectorFunks.Length);
            checkVec_mod.SetValueByFunks(vectorFunks, vectorResultMod_pair.FirstElement.data);
            checkVec_mod.Show();

            stopWatch.Reset();

            //Чистый гибридный метод Ньютона
            Console.WriteLine("\nSingle: #Hybrid_Method");
            var iterRecount = 4;
            Console.WriteLine($"Iter recount: {iterRecount}");
            var vectorResultHyb_pair = MethodNewton_SNAU.Hybrid_withSLAU(vectorStart, matrixFunks, vectorFunks, iterRecount, stopWatch);
            Console.WriteLine($"Time: {stopWatch.ElapsedTicks} ticks");
            Console.WriteLine("Count math.operation: " +
                              $"{countMathOper_LUP * (1 + (vectorResultDef_pair.SecondElement / iterRecount)) + (countMathOper_SLAU + 1) * vectorResultDef_pair.SecondElement}");
            Console.WriteLine($"Count iter: {vectorResultHyb_pair.SecondElement}");
            Console.Write("Result vector: ");
            vectorResultHyb_pair.FirstElement.Show();

            //Thread.Sleep(10000);
            stopWatch.Reset();

            //Прогон на k итераций деф.методом, а потом добивка мод.методом
            var k = 4;
            Console.WriteLine("\nMerge: #Def_method->#Mod_Method");
            var vectorResultMerge_pair = MethodNewton_SNAU.MergeMethods(vectorStart, matrixFunks, vectorFunks, stopWatch, k);
            Console.WriteLine($"Time: {stopWatch.ElapsedTicks} ticks");
            Console.WriteLine("Count math.operation: " +
                              $"{countMathOper_LUP * (1 + k) + (countMathOper_SLAU + 1) * vectorResultDef_pair.SecondElement }");
            Console.WriteLine($"Count iter: {vectorResultMerge_pair.SecondElement}");
            Console.Write("Result vector: ");
            vectorResultMerge_pair.FirstElement.Show();

            stopWatch.Reset();
            #endregion
        }
Exemplo n.º 11
0
        static public double KF_Gauss(ScalarFunk1 f, double defA, double a, double b, double alpha, int n)
        {
            //Вычисляем моменты от 0 до 2n - 1
            Vector vectorMoments = new Vector(2 * n);

            for (int i = 0; i < 2 * n; i++)
            {
                vectorMoments.data[i] = CountMoment(defA, a, b, alpha, i);
            }

            //Находим коеффициенты для W(x)
            Matrix matrixCoeff = new Matrix(n);

            FillMatrixCoeff(matrixCoeff, vectorMoments);
            Matrix matrixCoeff_L = new Matrix(n);
            Matrix matrixCoeff_U = new Matrix(n);
            Matrix matrixCoeff_P = new Matrix(n);

            LUP_decomposition.LUP(matrixCoeff, matrixCoeff_L, matrixCoeff_U, matrixCoeff_P);
            Vector vectorB_coeff = new Vector(n);

            for (int i = 0; i < n; i++)
            {
                vectorB_coeff.data[i] = -vectorMoments.data[n + i];
            }
            Vector vectorCoeff = LUP_decomposition.SLAU(matrixCoeff_L, matrixCoeff_U, matrixCoeff_P, vectorB_coeff);

            //Находим узлы из W(x)
            Vector      vectorX = new Vector(n);
            ScalarFunk1 funkW   = (double X) =>
            {
                double resultFunc = 0.0;
                for (int i = 0; i <= n; i++)
                {
                    resultFunc += (i != n) ? vectorCoeff.data[i] * Math.Pow(X, i) : Math.Pow(X, n);
                }
                return(resultFunc);
            };
            ScalarFunk1 funkW_Derivative = (double X) =>
            {
                double resultFuncDerivative = 0.0;
                for (int i = 0; i <= n; i++)
                {
                    resultFuncDerivative += (i != n) ? vectorCoeff.data[i] * Math.Pow(X, i - 1) * i : Math.Pow(X, n - 1) * n;
                }
                return(resultFuncDerivative);
            };
            var resultCount = MethodNewton_Scalar.DefualtMethod(a, b, funkW, funkW_Derivative);

            vectorX.SetValues(resultCount.FirstElement);

            //Решаем СЛАУ и находим Aj
            Matrix matrixX = new Matrix(n);

            FillMatrixX(matrixX, vectorX);
            Matrix matrixX_L = new Matrix(n);
            Matrix matrixX_U = new Matrix(n);
            Matrix matrixX_P = new Matrix(n);

            LUP_decomposition.LUP(matrixX, matrixX_L, matrixX_U, matrixX_P);
            Vector vectorB_X = new Vector(n);

            for (int i = 0; i < n; i++)
            {
                vectorB_X.data[i] = vectorMoments.data[i];
            }
            Vector vectorA = LUP_decomposition.SLAU(matrixX_L, matrixX_U, matrixX_P, vectorB_X);

            //Получем ответ по КФ
            double result = 0.0;

            for (int i = 0; i < n; i++)
            {
                result += vectorA.data[i] * f(vectorX.data[i]);
            }

            return(result);
        }
Exemplo n.º 12
0
        static public double AnalysisMethod_Opt(TypeKF typeKF, ScalarFunk1 f, double defA, double a, double b, double alpha, int n, double Eps)
        {
            double L       = 2;
            Vector vectorH = new Vector(3);

            vectorH.data[0] = b - a;
            vectorH.data[1] = vectorH.data[0] / L;
            vectorH.data[2] = vectorH.data[1] / L;

            //Эйткен
            Vector vectorS = new Vector(3);

            vectorS.data[0] = SKF(typeKF, f, defA, a, b, alpha, n, vectorH.data[0]);
            vectorS.data[1] = SKF(typeKF, f, defA, a, b, alpha, n, vectorH.data[1]);
            vectorS.data[2] = SKF(typeKF, f, defA, a, b, alpha, n, vectorH.data[2]);

            double m = -Math.Log((vectorS.data[2] - vectorS.data[1]) / (vectorS.data[1] - vectorS.data[0])) / Math.Log(L);

            double R = (vectorS.data[2] - vectorS.data[1]) / (Math.Pow(L, m) - 1);

            double h_opt = vectorH.data[2] * Math.Pow(Eps / Math.Abs(R), 1.0 / m);

            //Чтобы укладывался в отрезок [a, b]
            int k = (Int32)Math.Ceiling((b - a) / h_opt);

            Console.WriteLine($"Count opt: {k}");
            //double logK = Math.Log(k) / Math.Log(L);
            //logK = Math.Ceiling(logK);
            //k = (int)Math.Pow(L, logK);

            vectorH.data[1] = ((b - a) / k) * L * L;
            vectorH.data[2] = ((b - a) / k) * L;



            if (vectorH.data[1] > (b - a) || vectorH.data[2] > (b - a))
            {
                Console.WriteLine($"Count iter: {Math.Pow(L, 3)}");
                return(vectorS.data[2]);
            }
            else
            {
                int countIter = (int)k;

                double result = 0.0;

                double tempR = Double.PositiveInfinity;
                do
                {
                    countIter      *= (int)L;
                    vectorH.data[0] = vectorH.data[1];
                    vectorH.data[1] = vectorH.data[2];

                    vectorH.data[2] = vectorH.data[1] / L;
                    //Эйткен
                    vectorS.data[0] = SKF(typeKF, f, defA, a, b, alpha, n, vectorH.data[0]);
                    vectorS.data[1] = SKF(typeKF, f, defA, a, b, alpha, n, vectorH.data[1]);
                    vectorS.data[2] = SKF(typeKF, f, defA, a, b, alpha, n, vectorH.data[2]);

                    m = -Math.Log((Math.Abs(vectorS.data[2] - vectorS.data[1])) / (Math.Abs(vectorS.data[1] - vectorS.data[0]))) / Math.Log(L);

                    //Ричардсон

                    Matrix matrix_Cs_J = new Matrix(3);
                    for (int i = 0; i < matrix_Cs_J.N; i++)
                    {
                        for (int j = 0; j < matrix_Cs_J.N - 1; j++)
                        {
                            matrix_Cs_J.data[i][j] = Math.Pow(vectorH.data[i], m + j);
                        }
                        matrix_Cs_J.data[i][matrix_Cs_J.N - 1] = -1;
                    }

                    Matrix matrix_Cs_J_L = new Matrix(n);
                    Matrix matrix_Cs_J_U = new Matrix(n);
                    Matrix matrix_Cs_J_P = new Matrix(n);
                    LUP_decomposition.LUP(matrix_Cs_J, matrix_Cs_J_L, matrix_Cs_J_U, matrix_Cs_J_P);

                    Vector vector_Cs_J = LUP_decomposition.SLAU(matrix_Cs_J_L, matrix_Cs_J_U, matrix_Cs_J_P, -1 * vectorS);

                    result = vector_Cs_J.data[2];
                    tempR  = vectorS.data[2] - result;
                } while (Math.Abs(tempR) > Eps);
                Console.WriteLine($"Count iter: {countIter}");
                return(result);
            }
        }