public void TestGaussLegendreRuleIntervalEnd()
        {
            const int         order         = 19;
            GaussLegendreRule gaussLegendre = new GaussLegendreRule(StartA, StopA, order);

            Assert.AreEqual(gaussLegendre.IntervalEnd, StopA);
        }
        public void TestGaussLegendreRuleIntegrate2D(int order)
        {
            double appoximateArea = GaussLegendreRule.Integrate(TargetFunctionB, StartA, StopA, StartB, StopB, order);
            double relativeError  = Math.Abs(TargetAreaB - appoximateArea) / TargetAreaB;

            Assert.Less(relativeError, 1e-15);
        }
        public double CalculateFunctionalValue(List <GridValueInterpolator> muValueInterpolators)
        {
            var value = GaussLegendreRule.Integrate((x, y) =>
            {
                var functionValue = 0d;
                var densityValue  = 1d;
                var point         = VectorUtils.CreateVector(x, y);

                for (var centerIndex = 0; centerIndex < Settings.CentersSettings.CentersCount; centerIndex++)
                {
                    var centerData    = Settings.CentersSettings.CenterDatas[centerIndex];
                    var center        = centerData.Position;
                    var w             = centerData.W;
                    var a             = centerData.A;
                    var distanceValue = (point - center).L2Norm();
                    var muValue       = muValueInterpolators[centerIndex].GetGridValueAtPoint(x, y);
                    functionValue    += Math.Pow(muValue, 2) * (distanceValue / w + a) * densityValue;
                }

                return(functionValue);
            },
                                                    Settings.SpaceSettings.MinCorner[0],
                                                    Settings.SpaceSettings.MaxCorner[0],
                                                    Settings.SpaceSettings.MinCorner[1],
                                                    Settings.SpaceSettings.MaxCorner[1],
                                                    Settings.FuzzyPartitionPlacingCentersSettings.GaussLegendreIntegralOrder
                                                    );

            return(value);
        }
示例#4
0
        public double CalculateFunctionalValue()
        {
            var integralValue = GaussLegendreRule.Integrate((x, y) =>
            {
                var functionValue = 0d;
                var densityValue  = 1d;
                var psi           = _psiGridValueGetter.GetGridValueAtPoint(x, y);
                var point         = VectorUtils.CreateVector(x, y);

                for (var centerIndex = 0; centerIndex < _settings.CentersSettings.CentersCount; centerIndex++)
                {
                    var data       = _settings.CentersSettings.CenterDatas[centerIndex];
                    var position   = data.Position;
                    var distance   = (point - position).L2Norm();
                    var a          = data.A;
                    var w          = data.W;
                    var value      = (psi * psi) / ((distance / w + a) * densityValue);
                    functionValue += value;
                }

                return(functionValue);
            },
                                                            _settings.SpaceSettings.MinCorner[0],
                                                            _settings.SpaceSettings.MaxCorner[0],
                                                            _settings.SpaceSettings.MinCorner[1],
                                                            _settings.SpaceSettings.MaxCorner[1],
                                                            _settings.FuzzyPartitionPlacingCentersSettings.GaussLegendreIntegralOrder
                                                            );

            var functionalValue = 0.25d * integralValue;

            return(functionalValue);
        }
示例#5
0
        private void CalculateModel(INRA.SiriusQualityIrradiance.Interfaces.Rates rates, INRA.SiriusQualityIrradiance.Interfaces.Exogenous exogenous, INRA.SiriusQualityIrradiance.Interfaces.States states, CRA.AgroManagement.ActEvents actevents)
        {
            //GENERATED CODE END - PLACE YOUR CUSTOM CODE BELOW - Section1
            //Code written below will not be overwritten by a future code generation

            //Inputs
            double rho       = states.rhoLeaf;
            double tau       = states.tauLeaf;
            double alphaMean = states.ala;
            double sigma     = rho + tau;

            Func <double, double> f = null;

            double rhoh = (1 - Math.Sqrt(1 - sigma)) / (1 + Math.Sqrt(1 - sigma));

            if (useSphericalLeafDistrib == 1)
            {
                f = x => (1 - Math.Exp(-((2.0 * rhoh * CI * 0.5 / Math.Sin(Math.Max(0.00174533, x))) / (1 + CI * 0.5 / Math.Sin(Math.Max(0.00174533, x)))))) * Math.Cos(x) * Math.Sin(x);
            }
            else
            {
                double Chi = Math.Pow(alphaMean / 9.65, -0.6061) - 3;

                f = x => (1 - Math.Exp(-((2.0 * rhoh * (CI * (Math.Sqrt(Math.Pow(Chi, 2) + (1 / Math.Pow(Math.Tan(x), 2)))) / (Chi + 1.774 * Math.Pow(Chi + 1.182, -0.733)))) / (1 + (CI * (Math.Sqrt(Math.Pow(Chi, 2) + (1 / Math.Pow(Math.Tan(x), 2)))) / (Chi + 1.774 * Math.Pow(Chi + 1.182, -0.733))))))) * Math.Cos(x) * Math.Sin(x);
            }


            states.rhoCanopyDiff = 2.0 * GaussLegendreRule.Integrate(f, 0.0, Math.PI / 2.0, 30);


            //End of custom code. Do not place your custom code below. It will be overwritten by a future code generation.
            //PLACE YOUR CUSTOM CODE ABOVE - GENERATED CODE START - Section1
        }
        public void TestGaussLegendreRuleIntegration(int order)
        {
            double appoximateArea = GaussLegendreRule.Integrate(TargetFunctionA, StartA, StopA, order);
            double relativeError  = Math.Abs(TargetAreaA - appoximateArea) / TargetAreaA;

            Assert.Less(relativeError, 5e-16);
        }
示例#7
0
        public double BillinearForm(int k, int s, double t)
        {
            var integrand = fun((double x) => Mu(x, t) * FiDx(k, x) * FiDx(s, x)
                                + (Beta(x, t) * FiDx(k, x) + Omega(x, t) * Fi(x, k))
                                * Fi(x, s));

            (double a, double b) = GetIntegrationBounds(k, s);
            return(GaussLegendreRule.Integrate(integrand, a, b, 5));
        }
示例#8
0
        /********************************************************************************************
        * Public members, functions and properties
        ********************************************************************************************/

        public double AverageRapidityDependence(
            Func <double, double> function
            )
        {
            double rapidityCap = Param.PartonPeakRapidity;

            return(GaussLegendreRule.Integrate(function,
                                               -rapidityCap, +rapidityCap, Param.EMFQuadratureOrder) / (2 * rapidityCap));
        }
示例#9
0
        private void CalculateModel(INRA.SiriusQualityIrradiance.Interfaces.Rates rates, INRA.SiriusQualityIrradiance.Interfaces.Exogenous exogenous, INRA.SiriusQualityIrradiance.Interfaces.States states, CRA.AgroManagement.ActEvents actevents)
        {
            //GENERATED CODE END - PLACE YOUR CUSTOM CODE BELOW - Section1
            //Code written below will not be overwritten by a future code generation
            //Inputs
            double rho       = states.rhoLeaf;
            double tau       = states.tauLeaf;
            double alphaMean = states.ala;
            Dictionary <int, Tuple <double, double> > gai = states.layersGAI;
            double L_tot  = gai.Sum(x => x.Value.Item1 + x.Value.Item2);
            double sigma  = rho + tau;
            double Sum_kd = 0.0;

            Func <double, double> f = null;

            if (useSphericalLeafDistrib == 1)
            {
                f = x => (1 - Math.Exp(-(CI * Math.Sqrt(1.0 - sigma) * 0.5 / Math.Sin(Math.Max(0.00174533, x))) * L_tot)) * Math.Cos(x) * Math.Sin(x);
            }
            else
            {
                double Chi = Math.Pow(alphaMean / 9.65, -0.6061) - 3;
                f = x => (1 - Math.Exp(-(CI * Math.Sqrt(1.0 - sigma) * (Math.Sqrt(Math.Pow(Chi, 2) + (1 / Math.Pow(Math.Tan(x), 2)))) / (Chi + 1.774 * Math.Pow(Chi + 1.182, -0.733))) * L_tot)) * Math.Cos(x) * Math.Sin(x);
            }


            Sum_kd = Math.Max(1E-06, GaussLegendreRule.Integrate(f, 0.0, Math.PI / 2.0, 30));

            //Outputs
            states.k_dif = Math.Min(1.0, -(1 / L_tot) * Math.Log(1.0 - 2.0 * Sum_kd));


            double Sum_kdBlack = 0.0;

            Func <double, double> fBlack = null;

            if (useSphericalLeafDistrib == 1)
            {
                fBlack = x => (1 - Math.Exp(-(CI * 0.5 / Math.Sin(Math.Max(0.00174533, x))) * L_tot)) * Math.Cos(x) * Math.Sin(x);
            }
            else
            {
                double Chi = Math.Pow(alphaMean / 9.65, -0.6061) - 3;
                fBlack = x => (1 - Math.Exp(-(CI * (Math.Sqrt(Math.Pow(Chi, 2) + (1 / Math.Pow(Math.Tan(x), 2)))) / (Chi + 1.774 * Math.Pow(Chi + 1.182, -0.733))) * L_tot)) * Math.Cos(x) * Math.Sin(x);
            }


            Sum_kdBlack = Math.Max(1E-06, GaussLegendreRule.Integrate(fBlack, 0.0, Math.PI / 2.0, 30));

            //Outputs
            states.k_difBlack = Math.Min(1.0, -(1 / L_tot) * Math.Log(1.0 - 2.0 * Sum_kdBlack));


            //End of custom code. Do not place your custom code below. It will be overwritten by a future code generation.
            //PLACE YOUR CUSTOM CODE ABOVE - GENERATED CODE START - Section1
        }
        public static double IntegrateOverRealPlane(
            Func <double, double, double> integrand,
            double approxSupportRadius,
            int order
            )
        {
            Func <double, double, double> transformedIntegrand
                = MapIntegrandToUnitInterval(integrand, approxSupportRadius);

            return(GaussLegendreRule.Integrate(transformedIntegrand, -1, 1, -1, 1, order));
        }
        public T Value(IFunction <T> f)
        {
            var sum = LinearAlgebra.Value.GetZeroValue();

            for (var i = 0; i < _elements.Length - 1; i++)
            {
                LinearAlgebra.Value.Add(ref sum, GaussLegendreRule <T> .Integrate(f, _elements[i], _elements[i + 1], _order));
            }

            if (_isCircle)
            {
                LinearAlgebra.Value.Add(ref sum, GaussLegendreRule <T> .Integrate(f, _elements[^ 1], _elements[0], _order));
示例#12
0
        public void TestGaussLegendreRuleAbscissasWeightsViaIntegration()
        {
            const int         order         = 19;
            GaussLegendreRule gaussLegendre = new GaussLegendreRule(StartA, StopA, order);

            double[] abscissa = gaussLegendre.Abscissas;
            double[] weight   = gaussLegendre.Weights;

            for (int i = 0; i < gaussLegendre.Order; i++)
            {
                Assert.AreEqual(gaussLegendre.GetAbscissa(i), abscissa[i]);
                Assert.AreEqual(gaussLegendre.GetWeight(i), weight[i]);
            }
        }
        public void TestGaussLegendreRuleGetAbscissasGetWeightsOrderViaIntegration(int order)
        {
            GaussLegendreRule gaussLegendre = new GaussLegendreRule(StartA, StopA, order);

            double appoximateArea = 0;

            for (int i = 0; i < gaussLegendre.Order; i++)
            {
                appoximateArea += gaussLegendre.GetWeight(i) * TargetFunctionA(gaussLegendre.GetAbscissa(i));
            }

            double relativeError = Math.Abs(TargetAreaA - appoximateArea) / TargetAreaA;

            Assert.Less(relativeError, 5e-16);
        }
示例#14
0
        /// <summary>
        /// Computes the norms of room wave functions.
        /// Formula 2.86
        /// </summary>
        /// <returns>The norms of room wave functions.</returns>
        /// <param name="room">Room.</param>
        /// <param name="M">M.</param>
        /// <param name="N">N.</param>
        public static Complex[][] ComputeNormsOfRoomWaveFunctions(Room room, int M, int N)
        {
            var result = ComplexMatrix.Create2D(M, N);

            for (int m = 0; m < M; m++)
            {
                for (int n = 0; n < N; n++)
                {
                    result[m][n] = GaussLegendreRule.Integrate((x, y) =>
                    {
                        return(Math.Pow(ComputePhiRoom(room, m, n, x, y), 2.0));
                    }, 0.0, room.L_x, 0.0, room.L_y, 5);
                }
            }
            return(result);
        }
示例#15
0
        public double L(int s, int tIndex, double[] ui)
        {
            var t = GetApproximateTime(tIndex);

            var(a, b) = GetIntegrationBoundsForLinearFunctional(s);

            double l = GaussLegendreRule.Integrate(x => (F(x, t) - Condition.U0(t) * Omega(x, t)) * Fi(x, s), a, b, 5)
                       + Mu(1, t) * Fi(1, s) * Condition.U1(t);

            double sum = 0.0;

            for (int j = 1; j < N; j++)
            {
                sum += ui[j - 1] * BillinearForm(j, s, t);
            }
            return(l - sum);
        }
示例#16
0
        /// <summary>
        /// Computes the norms of the plate modes.
        /// Formula 2.102
        /// </summary>
        /// <returns>The norms of the plate modes.</returns>
        /// <param name="room">Room.</param>
        /// <param name="M">M.</param>
        /// <param name="N">N.</param>
        public static Complex[][] ComputeNormsOfThePlateModes(Plate plate, int P, int Q,
                                                              Func <Plate, int, int, double, double, double> func)
        {
            var result = ComplexMatrix.Create2D(P, Q);

            for (int p = 1; p <= P; p++)
            {
                for (int q = 1; q <= Q; q++)
                {
                    result[p - 1][q - 1] = GaussLegendreRule.Integrate((x, y) =>
                    {
                        return(Math.Pow(func(plate, p, q, x, y), 2.0));
                    }, 0.0, plate.L_x, 0.0, plate.L_y, 5);
                }
            }
            return(result);
        }
示例#17
0
文件: Analysis.cs 项目: Siubaak/IGA2D
        public Matrix <double> K()
        {
            Matrix <double> tmpK = Matrix <double> .Build.Dense(2 *Nodes.Count, 2 *Nodes.Count, 0);

            List <double>     ParaSpaceX = (new HashSet <double>(NurbsX.KnotVector)).ToList();
            List <double>     ParaSpaceY = (new HashSet <double>(NurbsY.KnotVector)).ToList();
            GaussLegendreRule IntegrateR = new GaussLegendreRule(ParaSpaceX[n / (ParaSpaceY.Count - 1)], ParaSpaceX[(n / (ParaSpaceY.Count - 1)) + 1], NurbsX.Order + 1);
            GaussLegendreRule IntegrateS = new GaussLegendreRule(ParaSpaceY[n % (ParaSpaceY.Count - 1)], ParaSpaceY[(n % (ParaSpaceY.Count - 1)) + 1], NurbsY.Order + 1);

            for (int i = 0; i != IntegrateR.Abscissas.Count(); ++i)
            {
                for (int j = 0; j != IntegrateS.Abscissas.Count(); ++j)
                {
                    Matrix <double> tmpB = B(IntegrateR.Abscissas[i], IntegrateS.Abscissas[j]);
                    tmpK += IntegrateR.Weights[i] * IntegrateS.Weights[j] * tmpB.Transpose() * D * tmpB * J(IntegrateR.Abscissas[i], IntegrateS.Abscissas[j]).Determinant() * t;
                }
            }
            return(tmpK);
        }
示例#18
0
        double L(int s, int tIndex, double[] ui, double[] vi)
        {
            var t    = GetApproximateTime(tIndex);
            var step = Step(tIndex);

            var(a, b) = GetIntegrationBoundsForLinearFunctional(s);

            double l = GaussLegendreRule.Integrate(x => P(x, t) * Fi(x, s), a, b, 5);

            double sum = 0;

            for (int j = 1; j < N - 1; j++)
            {
                double bf = BillinearForm(j, s);
                sum += bf * ui[j - 1];
                sum += step * W1 * bf * vi[j - 1];
            }

            return(l + sum);
        }
        /// <summary>
        /// Calculated gradient.
        /// </summary>
        /// <param name="centerPosition">Current optimal center position, τ*.</param>
        /// <returns>Gradient vector</returns>
        public Vector <double> CalculateGradientForCenter(Vector <double> centerPosition, GridValueInterpolator muValueInterpolator)
        {
            _centerPosition = centerPosition;

            if (Settings.SpaceSettings.MetricsType != MetricsType.Euclidean)
            {
                throw new NotImplementedException($"Визначення градієнту для метрики {Settings.SpaceSettings.MetricsType} не реалізовано");
            }

            var vector = Vector <double> .Build.Sparse(Settings.SpaceSettings.DimensionsCount);

            for (var i = 0; i < Settings.SpaceSettings.DimensionsCount; i++)
            {
                var dimensionIndex = i;

                var value = GaussLegendreRule.Integrate(
                    (x, y) =>
                {
                    var densityValue = 1d;
                    var mu           = muValueInterpolator.GetGridValueAtPoint(x, y);

                    var point = VectorUtils.CreateVector(x, y);
                    var distanceGradientValue = CalculateDistanceGradientValue(point, dimensionIndex);

                    var integralFunctionValue = distanceGradientValue * densityValue * mu * mu;

                    return(integralFunctionValue);
                },
                    Settings.SpaceSettings.MinCorner[0],
                    Settings.SpaceSettings.MaxCorner[0],
                    Settings.SpaceSettings.MinCorner[1],
                    Settings.SpaceSettings.MaxCorner[1],
                    Settings.FuzzyPartitionPlacingCentersSettings.GaussLegendreIntegralOrder
                    );

                vector[i] = value;
            }

            return(vector);
        }
示例#20
0
        /// <summary>
        /// Returns the integral of 0.25 * Θ(A + B*x + C*y) over the interval [-1,1]×[-1,1].
        /// </summary>
        public static double AveragedHeavisideStepFunctionWithLinearArgument(
            double A,
            double B,
            double C
            )
        {
            if (B == 0)
            {
                return(AveragedHeavisideStepFunctionWithLinearArgument(A, C));
            }
            else if (C == 0)
            {
                return(AveragedHeavisideStepFunctionWithLinearArgument(A, B));
            }
            else if (double.IsInfinity(A))
            {
                return(HeavisideStepFunction(A));
            }
            else if (double.IsInfinity(B))
            {
                return(AveragedHeavisideStepFunctionWithLinearArgument(A, B));
            }
            else if (double.IsInfinity(C))
            {
                return(AveragedHeavisideStepFunctionWithLinearArgument(A, C));
            }
            else
            {
                B = Math.Abs(B);
                C = Math.Abs(C);

                Func <double, double> integrand
                    = y => ((A + C * y) / B + 1) * HeavisideStepFunction(B - Math.Abs(A + C * y));

                return(HeavisideStepFunction(A - B - C)
                       + 0.5 * ((A - B) / C + 1) * HeavisideStepFunction(C - Math.Abs(A - B))
                       + 0.25 * GaussLegendreRule.Integrate(integrand, -1, 1, 10));
            }
        }
示例#21
0
文件: Analysis.cs 项目: Siubaak/IGA2D
        public List <List <double> > StressSample(Vector <double> Disp)
        {
            List <List <double> > Pxys       = new List <List <double> >();
            List <double>         ParaSpaceX = (new HashSet <double>(NurbsX.KnotVector)).ToList();
            List <double>         ParaSpaceY = (new HashSet <double>(NurbsY.KnotVector)).ToList();
            GaussLegendreRule     IntegrateR = new GaussLegendreRule(ParaSpaceX[n / (ParaSpaceY.Count - 1)], ParaSpaceX[(n / (ParaSpaceY.Count - 1)) + 1], NurbsX.Order + 1);
            GaussLegendreRule     IntegrateS = new GaussLegendreRule(ParaSpaceY[n % (ParaSpaceY.Count - 1)], ParaSpaceY[(n % (ParaSpaceY.Count - 1)) + 1], NurbsY.Order + 1);

            for (int i = 0; i != IntegrateR.Abscissas.Count(); ++i)
            {
                for (int j = 0; j != IntegrateS.Abscissas.Count(); ++j)
                {
                    Pxys.Add(new List <double> {
                        IntegrateR.Abscissas[i],
                        IntegrateS.Abscissas[j],
                        Stress(IntegrateR.Abscissas[i], IntegrateS.Abscissas[j], Disp)[0],
                        Stress(IntegrateR.Abscissas[i], IntegrateS.Abscissas[j], Disp)[1],
                        Stress(IntegrateR.Abscissas[i], IntegrateS.Abscissas[j], Disp)[2]
                    });
                }
            }
            return(Pxys);
        }
示例#22
0
        /// <summary>
        /// Computes the plate room projection coefficients.
        /// Formula 2.87
        /// </summary>
        /// <returns>The plate room projection coefficients.</returns>
        /// <param name="plate">Plate.</param>
        /// <param name="room">Room.</param>
        /// <param name="M">M.</param>
        /// <param name="N">N.</param>
        /// <param name="P">P.</param>
        /// <param name="Q">Q.</param>
        public static Complex[][][][] ComputePlateRoomProjectionCoefficients(Plate plate, Room room, int M, int N, int P, int Q)
        {
            var result = ComplexMatrix.Create4D(M, N, P, Q);

            for (int m = 0; m < M; m++)
            {
                for (int n = 0; n < N; n++)
                {
                    for (int p = 1; p <= P; p++)
                    {
                        for (int q = 1; q <= Q; q++)
                        {
                            result[m][n][p - 1][q - 1] = GaussLegendreRule.Integrate((x, y) =>
                            {
                                return(ComputePhiRoom(room, m, n, x + plate.DeltaX, y + plate.DeltaY)
                                       * ComputePhiPlateSimplySupported(plate, p, q, x, y));
                            }, 0.0, plate.L_x, 0.0, plate.L_y, 5);
                        }
                    }
                }
            }
            return(result);
        }
示例#23
0
        static void Main(string[] args)
        {
            /// Git test project
            Console.WriteLine("ASP joined the project");



            /// Simpsons Rule
            //---------------------------------------------
            Console.WriteLine("Simpson integration");
            Console.WriteLine("");

            // Composite approximation with 4 partitions
            double composite = SimpsonRule.IntegrateComposite(x => x * x, 0.0, 10.0, 4);

            // Approximate value using IntegrateComposite with 4 partitions is: 333.33333333333337
            Console.WriteLine("Approximate value using IntegrateComposite with 4 partitions is: " + composite);

            // Three point approximation
            double threePoint = SimpsonRule.IntegrateThreePoint(x => x * x, 0.0, 10.0);

            // Approximate value using IntegrateThreePoint is: 333.333333333333
            Console.WriteLine("Approximate value using IntegrateThreePoint is: " + threePoint);


            /// Gauss-Legendre integration
            //---------------------------------------------
            Console.WriteLine("");
            Console.WriteLine("Gauss-Legendre integration");
            Console.WriteLine("");

            // Create a 5-point Gauss-Legendre rule over the integration interval [0, 10]
            GaussLegendreRule rule = new GaussLegendreRule(0.0, 10.0, 5);

            double sum = 0;                      // Will hold the approximate value of the integral

            for (int i = 0; i < rule.Order; i++) // rule.Order = 5
            {
                // Access the ith abscissa and weight
                sum += rule.GetWeight(i) * rule.GetAbscissa(i) * rule.GetAbscissa(i);
            }

            // Approximate value is: 333.333333333333
            Console.WriteLine("Approximate value is: " + sum);

            // The order of the rule is: 5
            Console.WriteLine("The order of the rule is: " + rule.Order);

            // 1D integration using a 5-point Gauss-Legendre rule over the integration interval [0, 10]
            double integrate1D = GaussLegendreRule.Integrate(x => x * x * x, 0.0, 10.0, 5);

            // Approximate value of the 1D integral is: 333.333333333333
            Console.WriteLine("Approximate value of the 1D integral is: " + integrate1D);

            // 2D integration using a 5-point Gauss-Legendre rule over the integration interval [0, 10] X [1, 2]
            double integrate2D = GaussLegendreRule.Integrate((x, y) => (x * x) * (y * y), 0.0, 10.0, 1.0, 2.0, 5);

            // Approximate value of the 2D integral is: 777.777777777778
            Console.WriteLine("Approximate value of the 2D integral is: " + integrate2D);

            Console.ReadLine();
        }
示例#24
0
        /// <summary>
        /// Approximation of the definite integral of an analytic smooth complex function by double-exponential quadrature. When either or both limits are infinite, the integrand is assumed rapidly decayed to zero as x -> infinity.
        /// </summary>
        /// <param name="f">The analytic smooth complex function to integrate, defined on the real domain.</param>
        /// <param name="intervalBegin">Where the interval starts.</param>
        /// <param name="intervalEnd">Where the interval stops.</param>
        /// <param name="order">Defines an Nth order Gauss-Legendre rule. The order also defines the number of abscissas and weights for the rule. Precomputed Gauss-Legendre abscissas/weights for orders 2-20, 32, 64, 96, 100, 128, 256, 512, 1024 are used, otherwise they're calculated on the fly.</param>
        /// <returns>Approximation of the finite integral in the given interval.</returns>
        public static Complex GaussLegendre(Func <double, Complex> f, double intervalBegin, double intervalEnd, int order = 128)
        {
            // Reference:
            // Formula used for variable subsitution from
            // 1. Shampine, L. F. (2008). Vectorized adaptive quadrature in MATLAB. Journal of Computational and Applied Mathematics, 211(2), 131-140.
            // 2. quadgk.m, GNU Octave

            if (intervalBegin > intervalEnd)
            {
                return(-GaussLegendre(f, intervalEnd, intervalBegin, order));
            }

            // (-oo, oo) => [-1, 1]
            //
            // integral_(-oo)^(oo) f(x) dx = integral_(-1)^(1) f(g(t)) g'(t) dt
            // g(t) = t / (1 - t^2)
            // g'(t) = (1 + t^2) / (1 - t^2)^2
            if (double.IsInfinity(intervalBegin) && double.IsInfinity(intervalEnd))
            {
                Func <double, Complex> u = (t) =>
                {
                    return(f(t / (1 - t * t)) * (1 + t * t) / ((1 - t * t) * (1 - t * t)));
                };
                return(GaussLegendreRule.ContourIntegrate(u, -1, 1, order));
            }
            // [a, oo) => [0, 1]
            //
            // integral_(a)^(oo) f(x) dx = integral_(0)^(oo) f(a + t^2) 2 t dt
            //                           = integral_(0)^(1) f(a + g(s)^2) 2 g(s) g'(s) ds
            // g(s) = s / (1 - s)
            // g'(s) = 1 / (1 - s)^2
            else if (double.IsInfinity(intervalEnd))
            {
                Func <double, Complex> u = (s) =>
                {
                    return(2 * s * f(intervalBegin + (s / (1 - s)) * (s / (1 - s))) / ((1 - s) * (1 - s) * (1 - s)));
                };
                return(GaussLegendreRule.ContourIntegrate(u, 0, 1, order));
            }
            // (-oo, b] => [-1, 0]
            //
            // integral_(-oo)^(b) f(x) dx = -integral_(-oo)^(0) f(b - t^2) 2 t dt
            //                            = -integral_(-1)^(0) f(b - g(s)^2) 2 g(s) g'(s) ds
            // g(s) = s / (1 + s)
            // g'(s) = 1 / (1 + s)^2
            else if (double.IsInfinity(intervalBegin))
            {
                Func <double, Complex> u = (s) =>
                {
                    return(-2 * s * f(intervalEnd - s / (1 + s) * (s / (1 + s))) / ((1 + s) * (1 + s) * (1 + s)));
                };
                return(GaussLegendreRule.ContourIntegrate(u, -1, 0, order));
            }
            // [a, b] => [-1, 1]
            //
            // integral_(a)^(b) f(x) dx = integral_(-1)^(1) f(g(t)) g'(t) dt
            // g(t) = (b - a) * t * (3 - t^2) / 4 + (b + a) / 2
            // g'(t) = 3 / 4 * (b - a) * (1 - t^2)
            else
            {
                Func <double, Complex> u = (t) =>
                {
                    return(f((intervalEnd - intervalBegin) / 4 * t * (3 - t * t) + (intervalEnd + intervalBegin) / 2) * 3 * (intervalEnd - intervalBegin) / 4 * (1 - t * t));
                };
                return(GaussLegendreRule.ContourIntegrate(u, -1, 1, order));
            }
        }
示例#25
0
 public void TestGetGaussLegendreRuleIntervalBegin()
 {
     const int order = 19;
     GaussLegendreRule gaussLegendre = new GaussLegendreRule(StartA, StopA, order);
     Assert.AreEqual(gaussLegendre.IntervalBegin, StartA);
 }
示例#26
0
 double BillinearForm(int k, int s)
 {
     (double a, double b) = GetIntegrationBounds(k, s);
     return(-T0 *GaussLegendreRule.Integrate(x => FiDx(k, x) *FiDx(s, x), a, b, 5));
 }
示例#27
0
        public static double Integral(SubIntegral func, double min, double max, int count)
        {
            double res = GaussLegendreRule.Integrate(x => { return(func(x)); }, min, max, count);

            return(res);
        }
示例#28
0
        private static bool Integration()
        {
            Console.Write("Введите левый конец отрезка интегрирования по составной КФ Гаусса и КФ типа Гаусса: ");

            var left = 0d;

            while (!double.TryParse(Console.ReadLine(), out left) || !left.IsNumber())
            {
                Console.Write("Некорректное значение: введите вещественное число: ");
            }

            Console.Write("Введите правый конец отрезка интегрирования по составной КФ Гаусса и КФ типа Гаусса: ");

            var right = 0d;

            while (!double.TryParse(Console.ReadLine(), out right) || !right.IsNumber() || right <= left)
            {
                Console.Write("Некорректное значение: введите вещественное число, большее левого конца отрезка интегрирования: ");
            }

            Console.Write("Введите число промежутков деления отрезка интегрирования по составной КФ Гаусса: ");

            var segmentNumber = 0;

            while (!int.TryParse(Console.ReadLine(), out segmentNumber) || segmentNumber <= 0)
            {
                Console.Write("Некорректное значение: введите положительное целое число: ");
            }

            Console.Write("Введите число узлов для интегрирования по КФ Мелера: ");

            var nodeNumber = 0;

            while (!int.TryParse(Console.ReadLine(), out nodeNumber) || nodeNumber <= 0)
            {
                Console.Write("Некорректное значение: введите положительное целое число: ");
            }

            FormatExtensions.PrintDivider();

            var segmentLength = (right - left) / segmentNumber;

            var gaussIntegral     = Integrator.GaussIntegrate(x => FunctionForGauss(x) * WeightForGauss(x), left, right, segmentNumber);
            var gaussLikeIntegral = Integrator.GaussLikeIntegrate(FunctionForGauss, WeightForGauss, left, right, new Logger());
            var melerIntegral     = Integrator.MelerIntegrate(FunctionForMeler, nodeNumber);

            var gaussExpectedIntegral = GaussLegendreRule.Integrate(x => FunctionForGauss(x) * WeightForGauss(x), left, right, MathNetIntegrationNodeNumber);

            FormatExtensions.PrintDivider();

            Console.WriteLine($"Функция: f(x) = sin(x) | Вес: 1 / (x + 0.1)");
            Console.WriteLine($"Отрезок интегрирования: [{left.Format(5)}, {right.Format(5)}]");
            Console.WriteLine($"Фактическое значение интеграла: {gaussExpectedIntegral.Format()}");
            Console.WriteLine($"Число отрезков деления для КФ Гаусса: {segmentNumber}");
            Console.WriteLine($"Длина отрезка для КФ Гаусса: {segmentLength.Format()}\n");

            Console.WriteLine(
                $"Формула Гаусса\n" +
                $"Вычисленное приближенное значение: {gaussIntegral.Format()}\n" +
                $"Абсолютная фактическая погрешность: {Math.Abs(gaussExpectedIntegral - gaussIntegral).Format()}\n\n" +
                $"Формула типа Гаусса\n" +
                $"Вычисленное приближенное значение: {gaussLikeIntegral.Format()}\n" +
                $"Абсолютная фактическая погрешность: {Math.Abs(gaussExpectedIntegral - gaussLikeIntegral).Format()}\n\n");

            FormatExtensions.PrintDivider();

            Console.WriteLine($"Функция: f(x) = 1 / (1 + x^2) | Вес: 1 / sqrt(1 - x^2)");
            Console.WriteLine($"Отрезок интегрирования: [-1, 1]");
            Console.WriteLine($"Фактическое значение интеграла: {MelerExpectedIntegral.Format()}");
            Console.WriteLine($"Число узлов для КФ Мелера: {nodeNumber}\n");

            Console.WriteLine(
                $"Формула Мелера\n" +
                $"Вычисленное приближенное значение: {melerIntegral.Format()}\n" +
                $"Абсолютная фактическая погрешность: {Math.Abs(MelerExpectedIntegral - melerIntegral).Format()}\n\n");

            Console.WriteLine($"Чтобы выйти, нажмите \'Esc\'\n");

            if (Console.ReadKey().Key == ConsoleKey.Escape)
            {
                return(false);
            }

            return(true);
        }
示例#29
0
        public void TestGaussLegendreRuleGetAbscissasGetWeightsOrderViaIntegration(int order)
        {
            GaussLegendreRule gaussLegendre = new GaussLegendreRule(StartA, StopA, order);

            double appoximateArea = 0;
            for (int i = 0; i < gaussLegendre.Order; i++)
            {
                appoximateArea += gaussLegendre.GetWeight(i) * TargetFunctionA(gaussLegendre.GetAbscissa(i));
            }

            double relativeError = Math.Abs(TargetAreaA - appoximateArea) / TargetAreaA;
            Assert.Less(relativeError, 5e-16);
        }
示例#30
0
 /// <summary>
 /// Approximates a 2-dimensional definite integral using an Nth order Gauss-Legendre rule over the rectangle [a,b] x [c,d].
 /// </summary>
 /// <param name="f">The 2-dimensional analytic smooth function to integrate.</param>
 /// <param name="invervalBeginA">Where the interval starts for the first (inside) integral, exclusive and finite.</param>
 /// <param name="invervalEndA">Where the interval ends for the first (inside) integral, exclusive and finite.</param>
 /// <param name="invervalBeginB">Where the interval starts for the second (outside) integral, exclusive and finite.</param>
 /// /// <param name="invervalEndB">Where the interval ends for the second (outside) integral, exclusive and finite.</param>
 /// <returns>Approximation of the finite integral in the given interval.</returns>
 public static double OnRectangle(Func <double, double, double> f, double invervalBeginA, double invervalEndA, double invervalBeginB, double invervalEndB)
 {
     return(GaussLegendreRule.Integrate(f, invervalBeginA, invervalEndA, invervalBeginB, invervalEndB, 32));
 }
示例#31
0
        private void SetModelCoefficients()
        {
            XModelValues = new double[XValues.Rows, 1];

            var interval = 365d;

            var fourierModelValue = 0d;

            var w = 2 * Math.PI / interval;

            for (int i = 0; i < XValues.Rows; i++)
            {
                for (int n = 0; n < 20; n++)
                {
                    for (int m = 0; m < 20; m++)
                    {
                        var nValue = n;
                        var mValue = m;
                        var x      = XValues[i, FirstVariableIndex];
                        var y      = XValues[i, SecondVariableIndex];

                        var xyCosCosValue = Math.Cos(nValue * w * x / interval) * Math.Cos(mValue * w * y / interval);
                        var xySinCosValue = Math.Sin(nValue * w * x / interval) * Math.Cos(mValue * w * y / interval);
                        var xyCosSinValue = Math.Cos(nValue * w * x / interval) * Math.Sin(mValue * w * y / interval);
                        var xySinSinValue = Math.Sin(nValue * w * x / interval) * Math.Sin(mValue * w * y / interval);

                        var lambda = FourierModelHelper.GetLambdaParameter(nValue, mValue);
                        var alpha  = GaussLegendreRule.Integrate(
                            (_, _) => (x + y) * xyCosCosValue,
                            -interval,
                            interval,
                            -interval,
                            interval,
                            32) * (1d / (interval * interval));
                        var beta = GaussLegendreRule.Integrate(
                            (_, _) => (x + y) * xySinCosValue,
                            -interval,
                            interval,
                            -interval,
                            interval,
                            32) * (1d / (interval * interval));
                        var gamma = GaussLegendreRule.Integrate(
                            (_, _) => (x + y) * xyCosSinValue,
                            -interval,
                            interval,
                            -interval,
                            interval,
                            32) * (1d / (interval * interval));
                        var delta = GaussLegendreRule.Integrate(
                            (_, _) => (x + y) * xySinSinValue,
                            -interval,
                            interval,
                            -interval,
                            interval,
                            32) * (1d / (interval * interval));

                        fourierModelValue += lambda * (alpha * xyCosCosValue + beta * xySinCosValue +
                                                       gamma * xyCosSinValue + delta * xySinSinValue);
                    }
                }

                XModelValues[i, 0] = fourierModelValue;
            }

            YModelValues = new double[YValues.Rows, 1];
            for (int i = 0; i < YValues.Rows; i++)
            {
                YModelValues[i, 0] = YValues[i, 0];
            }

            SolveBModelValues();
        }