public void EllipticKIntegrals()
        {
            Interval i = Interval.FromEndpoints(0.0, 1.0);

            // http://mathworld.wolfram.com/CatalansConstant.html equation 37
            Assert.IsTrue(TestUtilities.IsNearlyEqual(
                              FunctionMath.Integrate(
                                  k => AdvancedMath.EllipticK(k),
                                  Interval.FromEndpoints(0.0, 1.0)),
                              2.0 * AdvancedMath.Catalan
                              ));

            Assert.IsTrue(TestUtilities.IsNearlyEqual(
                              FunctionMath.Integrate(
                                  k => AdvancedMath.EllipticK(k) * k,
                                  Interval.FromEndpoints(0.0, 1.0)),
                              1.0
                              ));

            Assert.IsTrue(TestUtilities.IsNearlyEqual(
                              FunctionMath.Integrate(
                                  k => AdvancedMath.EllipticK(k) / (1.0 + k),
                                  Interval.FromEndpoints(0.0, 1.0)),
                              Math.PI * Math.PI / 8.0
                              ));
        }
Esempio n. 2
0
        public void HypergeometricIntegral()
        {
            // A&S 15.3.1

            // F(a, b, c, x) = \frac{\Gamma(c)}{\Gamma(b) \Gamma(c - b)}
            // \int_{0}^{1} \! dt \, t^{b-1} (1 - t)^{c - b - 1} (1 - x t)^{-a}

            // Choose limits on a, b, c so that singularities of integrand are numerically integrable.

            foreach (double a in TestUtilities.GenerateRealValues(1.0, 10.0, 2))
            {
                foreach (double b in TestUtilities.GenerateRealValues(0.6, 10.0, 2))
                {
                    foreach (double c in TestUtilities.GenerateRealValues(b + 0.6, 10.0, 2))
                    {
                        foreach (double x in xs)
                        {
                            double I = FunctionMath.Integrate(
                                t => Math.Pow(t, b - 1.0) * Math.Pow(1.0 - t, c - b - 1.0) * Math.Pow(1.0 - x * t, -a),
                                Interval.FromEndpoints(0.0, 1.0)
                                );

                            double B = AdvancedMath.Beta(b, c - b);

                            Assert.IsTrue(TestUtilities.IsNearlyEqual(AdvancedMath.Hypergeometric2F1(a, b, c, x), I / B));
                        }
                    }
                }
            }
        }
        public void DistributionRawMomentIntegral()
        {
            foreach (ContinuousDistribution distribution in distributions)
            {
                foreach (int r in TestUtilities.GenerateIntegerValues(2, 32, 8))
                {
                    double M = distribution.RawMoment(r);
                    if (Double.IsInfinity(M) || Double.IsNaN(M))
                    {
                        continue;                                          // don't try to do a non-convergent integral
                    }
                    Func <double, double> f = delegate(double x) {
                        return(distribution.ProbabilityDensity(x) * Math.Pow(x, r));
                    };
                    try {
                        IntegrationResult MI = FunctionMath.Integrate(f, distribution.Support);
                        Console.WriteLine("{0} {1} {2} {3}", distribution.GetType().Name, r, M, MI);
                        Assert.IsTrue(MI.Estimate.ConfidenceInterval(0.99).ClosedContains(M));

                        /*
                         * if (M == 0.0) {
                         *  Assert.IsTrue(Math.Abs(MI) < TestUtilities.TargetPrecision);
                         * } else {
                         *  Assert.IsTrue(TestUtilities.IsNearlyEqual(M, MI));
                         * }
                         */
                    } catch (NonconvergenceException) {
                        Console.WriteLine("{0} {1} {2} NC", distribution.GetType().Name, r, M);
                    }
                }
            }
        }
 public void DistributionVarianceIntegral()
 {
     foreach (ContinuousDistribution distribution in distributions)
     {
         double v = distribution.Variance;
         // Skip distributions with infinite variance
         if (Double.IsNaN(v) || Double.IsInfinity(v))
         {
             continue;
         }
         // Determine target precision, which must be reduced for some cases where an integral singularity means that cannot achieve full precision
         double            e = TestUtilities.TargetPrecision;
         GammaDistribution gammaDistribution = distribution as GammaDistribution;
         if ((gammaDistribution != null) && (gammaDistribution.Shape < 1.0))
         {
             e = Math.Sqrt(e);
         }
         Func <double, double> f = delegate(double x) {
             double z = x - distribution.Mean;
             return(distribution.ProbabilityDensity(x) * z * z);
         };
         double C2 = FunctionMath.Integrate(f, distribution.Support, new IntegrationSettings()
         {
             RelativePrecision = e, AbsolutePrecision = 0.0
         }).Value;
         Assert.IsTrue(TestUtilities.IsNearlyEqual(C2, distribution.Variance, e));
     }
 }
Esempio n. 5
0
        public void FindExtremaNegativeGamma()
        {
            // https://en.wikipedia.org/wiki/Particular_values_of_the_Gamma_function#Other_constants

            Tuple <double, double>[] extrema = new Tuple <double, double>[] {
                Tuple.Create(-0.5040830082644554092582693045, -3.5446436111550050891219639933),
                Tuple.Create(-1.5734984731623904587782860437, 2.3024072583396801358235820396),
                Tuple.Create(-2.6107208684441446500015377157, -0.8881363584012419200955280294),
                Tuple.Create(-3.6352933664369010978391815669, 0.2451275398343662504382300889)
            };

            foreach (Tuple <double, double> extremum in extrema)
            {
                // We use brackets since we know the extremum must lie between the singularities.
                // We should be able to use the actual singularities at endpoints, but this doesn't work; look into it.

                Interval bracket = Interval.FromEndpoints(Math.Floor(extremum.Item1) + 0.01, Math.Ceiling(extremum.Item1) - 0.01);
                Extremum result;
                if (extremum.Item2 < 0.0)
                {
                    result = FunctionMath.FindMaximum(AdvancedMath.Gamma, bracket);
                }
                else
                {
                    result = FunctionMath.FindMinimum(AdvancedMath.Gamma, bracket);
                }
                Assert.IsTrue(result.Bracket.ClosedContains(extremum.Item1));
                Assert.IsTrue(result.Bracket.OpenContains(result.Location));
                Assert.IsTrue(TestUtilities.IsNearlyEqual(result.Value, extremum.Item2));
            }
        }
        public void AssociatedLegendreOrthonormalityL()
        {
            // don't let l and m get too big, or numerical integration will fail due to heavily oscilatory behavior

            int[] ells = TestUtilities.GenerateIntegerValues(1, 10, 4);
            for (int ki = 0; ki < ells.Length; ki++)
            {
                int k = ells[ki];
                for (int li = 0; li <= ki; li++)
                {
                    int l = ells[li];
                    foreach (int m in TestUtilities.GenerateUniformIntegerValues(0, Math.Min(k, l), 4))
                    {
                        Func <double, double> f = delegate(double x) {
                            return(OrthogonalPolynomials.LegendreP(k, m, x) * OrthogonalPolynomials.LegendreP(l, m, x));
                        };
                        double I = FunctionMath.Integrate(f, Interval.FromEndpoints(-1.0, 1.0));

                        Console.WriteLine("k={0} l={1} m={2} I={3}", k, l, m, I);

                        if (k == l)
                        {
                            Assert.IsTrue(TestUtilities.IsNearlyEqual(
                                              I, 2.0 / (2 * k + 1) * Math.Exp(AdvancedIntegerMath.LogFactorial(l + m) - AdvancedIntegerMath.LogFactorial(l - m))
                                              ));
                        }
                        else
                        {
                            Assert.IsTrue(Math.Abs(I) < TestUtilities.TargetPrecision);
                        }
                    }
                }
            }
        }
Esempio n. 7
0
        public void RootOfEi()
        {
            double x = FunctionMath.FindZero(AdvancedMath.IntegralEi, Interval.FromEndpoints(0.1, 1.0));

            Assert.IsTrue(TestUtilities.IsNearlyEqual(x, 0.37250741078136663446));
            Assert.IsTrue(Math.Abs(AdvancedMath.IntegralEi(x)) < TestUtilities.TargetPrecision);
        }
Esempio n. 8
0
        public void OdeAiry()
        {
            // This is the airy differential equation
            Func <double, double, double> f = (double x, double y) => x * y;

            // Solutions should be of the form f(x) = a Ai(x) + b Bi(x).
            // Given initial value of f and f', this equation plus the Wronskian can be solved to give
            //   a = \pi ( f Bi' - f' Bi )    b = \pi ( f' Ai - f Ai' )

            // Start with some initial conditions
            double x0  = 0.0;
            double y0  = 0.0;
            double yp0 = 1.0;

            // Find the a and b coefficients consistent with those values
            SolutionPair s0 = AdvancedMath.Airy(x0);
            double       a  = Math.PI * (y0 * s0.SecondSolutionDerivative - yp0 * s0.SecondSolutionValue);
            double       b  = Math.PI * (yp0 * s0.FirstSolutionValue - y0 * s0.FirstSolutionDerivative);

            Assert.IsTrue(TestUtilities.IsNearlyEqual(y0, a * s0.FirstSolutionValue + b * s0.SecondSolutionValue));
            Assert.IsTrue(TestUtilities.IsNearlyEqual(yp0, a * s0.FirstSolutionDerivative + b * s0.SecondSolutionDerivative));

            // Integrate to a new point (pick a negative one so we test left integration)
            double    x1     = -5.0;
            OdeResult result = FunctionMath.IntegrateConservativeOde(f, x0, y0, yp0, x1);

            Assert.IsTrue(TestUtilities.IsNearlyEqual(result.X, x1));
            Console.WriteLine(result.EvaluationCount);

            // The solution should still hold
            SolutionPair s1 = AdvancedMath.Airy(x1);

            Assert.IsTrue(TestUtilities.IsNearlyEqual(result.Y, a * s1.FirstSolutionValue + b * s1.SecondSolutionValue, result.Settings));
            Assert.IsTrue(TestUtilities.IsNearlyEqual(result.YPrime, a * s1.FirstSolutionDerivative + b * s1.SecondSolutionDerivative, result.Settings));
        }
Esempio n. 9
0
 public void DistributionVarianceIntegral()
 {
     foreach (Distribution distribution in distributions)
     {
         if (Double.IsNaN(distribution.Variance) || Double.IsInfinity(distribution.Variance))
         {
             continue;
         }
         double e = TestUtilities.TargetPrecision;
         // since a Gamma distribution with \alpha < 1 has a power law singularity and numerical integration cannot achieve full precision with such a singularity,
         // we reduce our precision requirement in this case
         GammaDistribution gammaDistribution = distribution as GammaDistribution; if ((gammaDistribution != null) && (gammaDistribution.ShapeParameter < 1.0))
         {
             e = Math.Sqrt(e);
         }
         Console.WriteLine(distribution.GetType().Name);
         Func <double, double> f = delegate(double x) {
             double z = x - distribution.Mean;
             return(distribution.ProbabilityDensity(x) * z * z);
         };
         double C2 = FunctionMath.Integrate(f, distribution.Support, new EvaluationSettings()
         {
             EvaluationBudget = 4096, RelativePrecision = e, AbsolutePrecision = 0.0
         }).Value;
         Console.WriteLine("  {0} {1}", distribution.StandardDeviation, Math.Sqrt(C2));
         Assert.IsTrue(TestUtilities.IsNearlyEqual(C2, distribution.Variance, e));
     }
 }
Esempio n. 10
0
 public void DistributionRawMomentIntegral()
 {
     foreach (Distribution distribution in distributions)
     {
         // range of moments is about 3 to 30
         foreach (int n in TestUtilities.GenerateIntegerValues(3, 30, 10))
         {
             double M = distribution.Moment(n);
             if (Double.IsInfinity(M) || Double.IsNaN(M))
             {
                 continue;                                          // don't try to do a non-convergent integral
             }
             Func <double, double> f = delegate(double x) {
                 return(distribution.ProbabilityDensity(x) * Math.Pow(x, n));
             };
             try {
                 double MI = FunctionMath.Integrate(f, distribution.Support);
                 Console.WriteLine("{0} {1} {2} {3}", distribution.GetType().Name, n, M, MI);
                 if (M == 0.0)
                 {
                     Assert.IsTrue(Math.Abs(MI) < TestUtilities.TargetPrecision);
                 }
                 else
                 {
                     Assert.IsTrue(TestUtilities.IsNearlyEqual(M, MI));
                 }
             } catch (NonconvergenceException) {
                 Console.WriteLine("{0} {1} {2} NC", distribution.GetType().Name, n, M);
             }
         }
     }
 }
Esempio n. 11
0
        public void DifferentiationTest()
        {
            int i = 0;

            foreach (TestDerivative test in derivatives)
            {
                i++;

                foreach (double x in TestUtilities.GenerateRealValues(0.1, 100.0, 5))
                {
                    UncertainValue nd = FunctionMath.Differentiate(test.Function, x);
                    double         ed = test.Derivative(x);
                    Console.WriteLine("{0} f'({1}) = {2} = {3}", i, x, nd, ed);

                    Console.WriteLine(
                        //Assert.IsTrue(
                        nd.ConfidenceInterval(0.999).ClosedContains(ed)
                        );

                    /*
                     *  TestUtilities.IsNearlyEqual(
                     *  FunctionMath.Differentiate(test.Function, x),
                     *  test.Derivative(x),
                     *  Math.Pow(2, -42)
                     */
                }
            }
        }
Esempio n. 12
0
        public void RootOfPsi()
        {
            double x = FunctionMath.FindZero(AdvancedMath.Psi, 1.5);

            Assert.IsTrue(TestUtilities.IsNearlyEqual(x, 1.46163214496836234126));
            Assert.IsTrue(AdvancedMath.Psi(x) < TestUtilities.TargetPrecision);
        }
Esempio n. 13
0
        public void EllipticKCatalanIntegral()
        {
            System.Diagnostics.Stopwatch timer = System.Diagnostics.Stopwatch.StartNew();

            Interval i = Interval.FromEndpoints(0.0, 1.0);

            // http://mathworld.wolfram.com/CatalansConstant.html equation 37

            Func <double, double> f1 = delegate(double k) {
                return(AdvancedMath.EllipticK(k));
            };

            Assert.IsTrue(TestUtilities.IsNearlyEqual(
                              FunctionMath.Integrate(f1, i), 2.0 * AdvancedMath.Catalan
                              ));

            Func <double, double> f2 = delegate(double k) {
                return(AdvancedMath.EllipticK(k) * k);
            };

            Assert.IsTrue(TestUtilities.IsNearlyEqual(
                              FunctionMath.Integrate(f2, i), 1.0
                              ));

            timer.Stop();
            Console.WriteLine(timer.ElapsedTicks);
        }
Esempio n. 14
0
        // COrrel Making for Hybrid Method!
        public SymmetricMatrix MakeCorrel(int n, Grid grid)
        {
            //Correlation between Z , Z_1 and Z_2
            //integrationCalcul
            Func <double, double> func     = t => (double)Math.Pow((1 * grid.get_Step() - t), (H - 0.5)) * Math.Pow((2 * grid.get_Step() - t), (H - 0.5));
            EvaluationSettings    settings = new EvaluationSettings();

            settings.AbsolutePrecision = 1.0E-9;
            settings.RelativePrecision = 0.0;
            IntegrationResult integresult = FunctionMath.Integrate(func, Meta.Numerics.Interval.FromEndpoints(0.0, grid.get_Step()), settings);

            #region Correlation Calcul (correl Matrix)
            SymmetricMatrix correl = new SymmetricMatrix(3);
            for (int i = 0; i < 3; i++)
            {
                correl[i, i] = 1.0;
            }
            double var_0 = (double)1 / n;
            double var_1 = (double)1 / (Math.Pow(n, 2 * (H - 0.5) + 1) * (2 * (H - 0.5) + 1));
            double var_2 = (double)Math.Pow(2, 2 * (H - 0.5) + 1) / (Math.Pow(n, 2 * (H - 0.5) + 1) * (2 * (H - 0.5) + 1));
            correl[1, 0] = (double)1 / (Math.Pow(n, H + 0.5) * (H + 0.5)) / (Math.Pow(var_0 * var_1, 0.5));
            correl[2, 0] = (double)(Math.Pow(2, H + 0.5) - 1) / (Math.Pow(n, H + 0.5) * (H + 0.5)) / (Math.Pow(var_0 * var_2, 0.5));
            correl[2, 1] = integresult.Value / (Math.Pow(var_2 * var_1, 0.5));
            #endregion
            return(correl);
        }
Esempio n. 15
0
        public void IntegralEiZero()
        {
            // Value of zero documented at https://dlmf.nist.gov/6.13
            double x0 = FunctionMath.FindZero(AdvancedMath.IntegralEi, 1.0);

            Assert.IsTrue(TestUtilities.IsNearlyEqual(x0, 0.37250741078136663446));
        }
Esempio n. 16
0
        public void JacobiIntegrals()
        {
            foreach (double k in TestUtilities.GenerateRealValues(1.0E-1, 1.0, 4))
            {
                // DLMF 22.14.18 says
                //   \int_{0}^{K(k)} \ln(\dn(t, k)) \, dt = \frac{1}{2} K(k) \ln k'

                double K = AdvancedMath.EllipticK(k);

                double k1 = Math.Sqrt(1.0 - k * k);

                double I1 = FunctionMath.Integrate(
                    x => Math.Log(AdvancedMath.JacobiDn(x, k)),
                    Interval.FromEndpoints(0.0, K)
                    );

                Assert.IsTrue(TestUtilities.IsNearlyEqual(I1, K / 2.0 * Math.Log(k1)));

                // If k is small, log(k1) is subject to cancellation error, so don't pick k too small.

                // It also gives values for the analogous integrals with \sn and \cn,
                // but their values involve K'(k), for which we don't have a method.

                // Mathworld (http://mathworld.wolfram.com/CompleteEllipticIntegraloftheSecondKind.html) says
                //   \int_{0}^{K(k)} \dn^2(t, k) = E(k)

                double I2 = FunctionMath.Integrate(
                    u => MoreMath.Sqr(AdvancedMath.JacobiDn(u, k)),
                    Interval.FromEndpoints(0.0, K)
                    );

                Assert.IsTrue(TestUtilities.IsNearlyEqual(I2, AdvancedMath.EllipticE(k)));
            }
        }
Esempio n. 17
0
        public void OdeSine()
        {
            // The sine and cosine functions satisfy
            //   y'' = - y
            // This is perhaps the simplest conservative differential equation.
            // (i.e. right hand side depends only on y, not y')

            Func <double, double, double> f = (double x, double y) => - y;

            int         count    = 0;
            OdeSettings settings = new OdeSettings()
            {
                Listener = (OdeResult r) => {
                    Assert.IsTrue(TestUtilities.IsNearlyEqual(
                                      MoreMath.Sqr(r.Y) + MoreMath.Sqr(r.YPrime), 1.0, r.Settings
                                      ));
                    Assert.IsTrue(TestUtilities.IsNearlyEqual(
                                      r.Y, MoreMath.Sin(r.X), r.Settings
                                      ));
                    count++;
                }
            };
            OdeResult result = FunctionMath.IntegrateConservativeOde(f, 0.0, 0.0, 1.0, 5.0, settings);

            Assert.IsTrue(TestUtilities.IsNearlyEqual(result.Y, MoreMath.Sin(5.0)));
            Assert.IsTrue(count > 0);
        }
Esempio n. 18
0
 public void IntegralE1Integral()
 {
     // A & S 5.1.33
     Assert.IsTrue(TestUtilities.IsNearlyEqual(
                       FunctionMath.Integrate(t => MoreMath.Sqr(AdvancedMath.IntegralE(1, t)), 0.0, Double.PositiveInfinity),
                       2.0 * Math.Log(2.0)
                       ));
 }
Esempio n. 19
0
        public void OdeSine()
        {
            Func <double, double, double> f = (double x, double y) => - y;
            double y1 = FunctionMath.SolveConservativeOde(f, 0.0, 0.0, 1.0, 5.0);

            Console.WriteLine(y1);
            Assert.IsTrue(TestUtilities.IsNearlyEqual(y1, MoreMath.Sin(5.0)));
        }
Esempio n. 20
0
 /// <summary>
 /// Computes the expectation value of the given function.
 /// </summary>
 /// <param name="f">The function.</param>
 /// <returns>The expectation value of the function.</returns>
 /// <exception cref="ArgumentNullException"><paramref name="f"/> is <see langword="null"/>.</exception>
 public virtual double ExpectationValue(Func <double, double> f)
 {
     if (f == null)
     {
         throw new ArgumentNullException(nameof(f));
     }
     return(FunctionMath.Integrate(x => f(x) * ProbabilityDensity(x), Support).Estimate.Value);
 }
Esempio n. 21
0
        public void Bug5505()
        {
            // finding the root of x^3 would fail with a NonconvergenceException because our termination criterion tested only
            // for small relative changes in x; adding a test for small absolute changes too solved the problem
            double x0 = FunctionMath.FindZero(delegate(double x) { return(x * x * x); }, 1.0);

            Assert.IsTrue(Math.Abs(x0) < TestUtilities.TargetPrecision);
        }
Esempio n. 22
0
        public void DistributionProbabilityIntegral()
        {
            Random rng = new Random(1);

            // if integral is very small, we still want to get it very accurately
            IntegrationSettings settings = new IntegrationSettings()
            {
                AbsolutePrecision = 0.0
            };

            foreach (ContinuousDistribution distribution in distributions)
            {
                if (distribution is BetaDistribution b && ((b.Alpha < 1.0) || (b.Beta < 1.0)))
                {
                    continue;
                }

                for (int i = 0; i < 4; i++)
                {
                    double x;
                    if (Double.IsNegativeInfinity(distribution.Support.LeftEndpoint) && Double.IsPositiveInfinity(distribution.Support.RightEndpoint))
                    {
                        // pick an exponentially distributed random point with a random sign
                        double y = rng.NextDouble();
                        x = -Math.Log(y);
                        if (rng.NextDouble() < 0.5)
                        {
                            x = -x;
                        }
                    }
                    else if (Double.IsPositiveInfinity(distribution.Support.RightEndpoint))
                    {
                        // pick an exponentially distributed random point
                        double y = rng.NextDouble();
                        x = distribution.Support.LeftEndpoint - Math.Log(y);
                    }
                    else
                    {
                        // pick a random point within the support
                        x = distribution.Support.LeftEndpoint + rng.NextDouble() * distribution.Support.Width;
                    }
                    double P = FunctionMath.Integrate(distribution.ProbabilityDensity, Interval.FromEndpoints(distribution.Support.LeftEndpoint, x), settings).Value;
                    double Q = FunctionMath.Integrate(distribution.ProbabilityDensity, Interval.FromEndpoints(x, distribution.Support.RightEndpoint), settings).Value;
                    if (!TestUtilities.IsNearlyEqual(P + Q, 1.0))
                    {
                        // the numerical integral for the triangular distribution can be inaccurate, because
                        // its locally low-polynomial behavior fools the integration routine into thinking it need
                        // not integrate as much near the inflection point as it must; this is a problem
                        // of the integration routine (or arguably the integral), not the triangular distribution,
                        // so skip it here
                        continue;
                    }

                    Assert.IsTrue(TestUtilities.IsNearlyEqual(P, distribution.LeftProbability(x)));
                    Assert.IsTrue(TestUtilities.IsNearlyEqual(Q, distribution.RightProbability(x)));
                }
            }
        }
        public void BesselWeberIntegral()
        {
            Func <double, double> f = delegate(double t) {
                return(Math.Exp(-t * t) * AdvancedMath.BesselJ(0, t) * t);
            };
            Interval r = Interval.FromEndpoints(0.0, Double.PositiveInfinity);

            Assert.IsTrue(TestUtilities.IsNearlyEqual(FunctionMath.Integrate(f, r).Estimate.Value, Math.Exp(-1.0 / 4.0) / 2.0));
        }
Esempio n. 24
0
        public void RootOfJ0()
        {
            Func <double, double> f = delegate(double x) {
                return(AdvancedMath.BesselJ(0, x));
            };
            double y = FunctionMath.FindZero(f, Interval.FromEndpoints(2.0, 4.0));

            Assert.IsTrue(TestUtilities.IsNearlyEqual(y, 2.40482555769577276862));
        }
Esempio n. 25
0
 public void FindMaximaFromPoint()
 {
     foreach (TestExtremum testExtremum in testMaxima)
     {
         Extremum extremum = FunctionMath.FindMaximum(testExtremum.Function, testExtremum.Interval.Midpoint);
         Assert.IsTrue(TestUtilities.IsNearlyEqual(extremum.Location, testExtremum.Location, Math.Sqrt(TestUtilities.TargetPrecision)));
         Assert.IsTrue(TestUtilities.IsNearlyEqual(extremum.Value, testExtremum.Value, TestUtilities.TargetPrecision));
     }
 }
Esempio n. 26
0
 public void IntegralEiE1Integrals()
 {
     // Here are a couple unusual integrals involving both Ei and E1
     // https://nvlpubs.nist.gov/nistpubs/jres/73B/jresv73Bn3p191_A1b.pdf
     Assert.IsTrue(TestUtilities.IsNearlyEqual(
                       FunctionMath.Integrate(x => Math.Exp(-x) * AdvancedMath.IntegralE(1, x) * AdvancedMath.IntegralEi(x), 0.0, Double.PositiveInfinity),
                       -Math.PI * Math.PI / 12.0
                       ));
 }
Esempio n. 27
0
        public void OdeErf()
        {
            Func <double, double, double> rhs = (double t, double u) =>
                                                2.0 / Math.Sqrt(Math.PI) * Math.Exp(-t * t);

            OdeResult r = FunctionMath.IntegrateOde(rhs, 0.0, 0.0, 5.0);

            Console.WriteLine(r.Y);
        }
Esempio n. 28
0
 public void IntegrateTestIntegrals()
 {
     for (int i = 0; i < integrals.Length; i++)
     {
         TestIntegral integral = integrals[i];
         double       result   = FunctionMath.Integrate(integral.Integrand, integral.Range);
         Assert.IsTrue(TestUtilities.IsNearlyEqual(result, integral.Result));
     }
 }
Esempio n. 29
0
        public static void IntegrateOde()
        {
            Func <double, double, double> rhs = (x, y) => - x * y;
            OdeResult sln = FunctionMath.IntegrateOde(rhs, 0.0, 1.0, 2.0);

            Console.WriteLine($"Numeric solution y({sln.X}) = {sln.Y}.");
            Console.WriteLine($"Required {sln.EvaluationCount} evaluations.");
            Console.WriteLine($"Analytic solution y({sln.X}) = {Math.Exp(-MoreMath.Sqr(sln.X) / 2.0)}");

            // Lotka-Volterra equations
            double A = 0.1;
            double B = 0.02;
            double C = 0.4;
            double D = 0.02;
            Func <double, IReadOnlyList <double>, IReadOnlyList <double> > lkRhs = (t, y) => {
                return(new double[] {
                    A *y[0] - B * y[0] * y[1], D *y[0] * y[1] - C * y[1]
                });
            };
            MultiOdeSettings lkSettings = new MultiOdeSettings()
            {
                Listener = r => { Console.WriteLine($"t={r.X} rabbits={r.Y[0]}, foxes={r.Y[1]}"); }
            };

            MultiFunctionMath.IntegrateOde(lkRhs, 0.0, new double[] { 20.0, 10.0 }, 50.0, lkSettings);

            Func <double, IReadOnlyList <double>, IReadOnlyList <double> > rhs1 = (x, u) => {
                return(new double[] { u[1], -u[0] });
            };
            MultiOdeSettings settings1 = new MultiOdeSettings()
            {
                EvaluationBudget = 100000
            };
            MultiOdeResult result1 = MultiFunctionMath.IntegrateOde(
                rhs1, 0.0, new double[] { 0.0, 1.0 }, 500.0, settings1
                );
            double s1 = MoreMath.Sqr(result1.Y[0]) + MoreMath.Sqr(result1.Y[1]);

            Console.WriteLine($"y({result1.X}) = {result1.Y[0]}, (y)^2 + (y')^2 = {s1}");
            Console.WriteLine($"Required {result1.EvaluationCount} evaluations.");

            Func <double, double, double> rhs2 = (x, y) => - y;
            OdeSettings settings2 = new OdeSettings()
            {
                EvaluationBudget = 100000
            };
            OdeResult result2 = FunctionMath.IntegrateConservativeOde(
                rhs2, 0.0, 0.0, 1.0, 500.0, settings2
                );
            double s2 = MoreMath.Sqr(result2.Y) + MoreMath.Sqr(result2.YPrime);

            Console.WriteLine($"y({result2.X}) = {result2.Y}, (y)^2 + (y')^2 = {s2}");
            Console.WriteLine($"Required {result2.EvaluationCount} evaluations");

            Console.WriteLine(MoreMath.Sin(500.0));
        }
Esempio n. 30
0
 public void FindMinimaFromPoint()
 {
     foreach (TestExtremum testExtremum in testMinima)
     {
         Extremum extremum = FunctionMath.FindMinimum(testExtremum.Function, testExtremum.Interval.Midpoint);
         Assert.IsTrue(TestUtilities.IsNearlyEqual(extremum.Location, testExtremum.Location, Math.Sqrt(TestUtilities.TargetPrecision)));
         Assert.IsTrue(TestUtilities.IsNearlyEqual(extremum.Value, testExtremum.Value, TestUtilities.TargetPrecision));
         //if (!Double.IsNaN(testMinimum.Curvature)) Assert.IsTrue(TestUtilities.IsNearlyEqual(minimum.Curvature, testMinimum.Curvature, 0.05));
     }
 }