private static int Math_Exp(ILuaState lua)
 {
     lua.PushNumber(Math.Exp(lua.L_CheckNumber(1)));
     return(1);
 }
Example #2
0
        /// <summary>
        /// Force a root found by a non-bracketing solver to lie on a specified side,
        /// as if the solver were a bracketing one.
        /// </summary>
        /// <param name="maxEval"> maximal number of new evaluations of the function
        /// (evaluations already done for finding the root should have already been subtracted
        /// from this number) </param>
        /// <param name="f"> function to solve </param>
        /// <param name="bracketing"> bracketing solver to use for shifting the root </param>
        /// <param name="baseRoot"> original root found by a previous non-bracketing solver </param>
        /// <param name="min"> minimal bound of the search interval </param>
        /// <param name="max"> maximal bound of the search interval </param>
        /// <param name="allowedSolution"> the kind of solutions that the root-finding algorithm may
        /// accept as solutions. </param>
        /// <returns> a root approximation, on the specified side of the exact root </returns>
        /// <exception cref="NoBracketingException"> if the function has the same sign at the
        /// endpoints. </exception>
//JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET:
//ORIGINAL LINE: public static double forceSide(final int maxEval, final org.apache.commons.math3.analysis.UnivariateFunction f, final BracketedUnivariateSolver<org.apache.commons.math3.analysis.UnivariateFunction> bracketing, final double baseRoot, final double min, final double max, final AllowedSolution allowedSolution) throws org.apache.commons.math3.exception.NoBracketingException
        public static double ForceSide(int maxEval, UnivariateFunction f, BracketedUnivariateSolver <UnivariateFunction> bracketing, double baseRoot, double min, double max, AllowedSolution allowedSolution)
        {
            if (allowedSolution == AllowedSolution.ANY_SIDE)
            {
                // no further bracketing required
                return(baseRoot);
            }

            // find a very small interval bracketing the root
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final double step = org.apache.commons.math3.util.FastMath.max(bracketing.getAbsoluteAccuracy(), org.apache.commons.math3.util.FastMath.abs(baseRoot * bracketing.getRelativeAccuracy()));
            double step          = FastMath.Max(bracketing.GetAbsoluteAccuracy(), FastMath.Abs(baseRoot * bracketing.GetRelativeAccuracy()));
            double xLo           = FastMath.Max(min, baseRoot - step);
            double fLo           = f.Value(xLo);
            double xHi           = FastMath.Min(max, baseRoot + step);
            double fHi           = f.Value(xHi);
            int    remainingEval = maxEval - 2;

            while (remainingEval > 0)
            {
                if ((fLo >= 0 && fHi <= 0) || (fLo <= 0 && fHi >= 0))
                {
                    // compute the root on the selected side
                    return(bracketing.Solve(remainingEval, f, xLo, xHi, baseRoot, allowedSolution));
                }

                // try increasing the interval
                bool changeLo = false;
                bool changeHi = false;
                if (fLo < fHi)
                {
                    // increasing function
                    if (fLo >= 0)
                    {
                        changeLo = true;
                    }
                    else
                    {
                        changeHi = true;
                    }
                }
                else if (fLo > fHi)
                {
                    // decreasing function
                    if (fLo <= 0)
                    {
                        changeLo = true;
                    }
                    else
                    {
                        changeHi = true;
                    }
                }
                else
                {
                    // unknown variation
                    changeLo = true;
                    changeHi = true;
                }

                // update the lower bound
                if (changeLo)
                {
                    xLo = FastMath.Max(min, xLo - step);
                    fLo = f.Value(xLo);
                    remainingEval--;
                }

                // update the higher bound
                if (changeHi)
                {
                    xHi = FastMath.Min(max, xHi + step);
                    fHi = f.Value(xHi);
                    remainingEval--;
                }
            }

            throw new NoBracketingException(LocalizedFormats.FAILED_BRACKETING, xLo, xHi, fLo, fHi, maxEval - remainingEval, maxEval, baseRoot, min, max);
        }
Example #3
0
        /// <summary>
        /// This method attempts to find two values a and b satisfying <ul>
        /// <li> {@code lowerBound <= a < initial < b <= upperBound} </li>
        /// <li> {@code f(a) * f(b) <= 0} </li>
        /// </ul>
        /// If {@code f} is continuous on {@code [a,b]}, this means that {@code a}
        /// and {@code b} bracket a root of {@code f}.
        /// <para>
        /// The algorithm checks the sign of \( f(l_k) \) and \( f(u_k) \) for increasing
        /// values of k, where \( l_k = max(lower, initial - \delta_k) \),
        /// \( u_k = min(upper, initial + \delta_k) \), using recurrence
        /// \( \delta_{k+1} = r \delta_k + q, \delta_0 = 0\) and starting search with \( k=1 \).
        /// The algorithm stops when one of the following happens: <ul>
        /// <li> at least one positive and one negative value have been found --  success!</li>
        /// <li> both endpoints have reached their respective limits -- NoBracketingException </li>
        /// <li> {@code maximumIterations} iterations elapse -- NoBracketingException </li></ul>
        /// </para>
        /// <para>
        /// If different signs are found at first iteration ({@code k=1}), then the returned
        /// interval will be \( [a, b] = [l_1, u_1] \). If different signs are found at a later
        /// iteration {@code k>1}, then the returned interval will be either
        /// \( [a, b] = [l_{k+1}, l_{k}] \) or \( [a, b] = [u_{k}, u_{k+1}] \). A root solver called
        /// with these parameters will therefore start with the smallest bracketing interval known
        /// at this step.
        /// </para>
        /// <para>
        /// Interval expansion rate is tuned by changing the recurrence parameters {@code r} and
        /// {@code q}. When the multiplicative factor {@code r} is set to 1, the sequence is a
        /// simple arithmetic sequence with linear increase. When the multiplicative factor {@code r}
        /// is larger than 1, the sequence has an asymptotically exponential rate. Note than the
        /// additive parameter {@code q} should never be set to zero, otherwise the interval would
        /// degenerate to the single initial point for all values of {@code k}.
        /// </para>
        /// <para>
        /// As a rule of thumb, when the location of the root is expected to be approximately known
        /// within some error margin, {@code r} should be set to 1 and {@code q} should be set to the
        /// order of magnitude of the error margin. When the location of the root is really a wild guess,
        /// then {@code r} should be set to a value larger than 1 (typically 2 to double the interval
        /// length at each iteration) and {@code q} should be set according to half the initial
        /// search interval length.
        /// </para>
        /// <para>
        /// As an example, if we consider the trivial function {@code f(x) = 1 - x} and use
        /// {@code initial = 4}, {@code r = 1}, {@code q = 2}, the algorithm will compute
        /// {@code f(4-2) = f(2) = -1} and {@code f(4+2) = f(6) = -5} for {@code k = 1}, then
        /// {@code f(4-4) = f(0) = +1} and {@code f(4+4) = f(8) = -7} for {@code k = 2}. Then it will
        /// return the interval {@code [0, 2]} as the smallest one known to be bracketing the root.
        /// As shown by this example, the initial value (here {@code 4}) may lie outside of the returned
        /// bracketing interval.
        /// </para> </summary>
        /// <param name="function"> function to check </param>
        /// <param name="initial"> Initial midpoint of interval being expanded to
        /// bracket a root. </param>
        /// <param name="lowerBound"> Lower bound (a is never lower than this value). </param>
        /// <param name="upperBound"> Upper bound (b never is greater than this
        /// value). </param>
        /// <param name="q"> additive offset used to compute bounds sequence (must be strictly positive) </param>
        /// <param name="r"> multiplicative factor used to compute bounds sequence </param>
        /// <param name="maximumIterations"> Maximum number of iterations to perform </param>
        /// <returns> a two element array holding the bracketing values. </returns>
        /// <exception cref="NoBracketingException"> if function cannot be bracketed in the search interval </exception>
//JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET:
//ORIGINAL LINE: public static double[] bracket(final org.apache.commons.math3.analysis.UnivariateFunction function, final double initial, final double lowerBound, final double upperBound, final double q, final double r, final int maximumIterations) throws org.apache.commons.math3.exception.NoBracketingException
        public static double[] Bracket(UnivariateFunction function, double initial, double lowerBound, double upperBound, double q, double r, int maximumIterations)
        {
            if (function == null)
            {
                throw new NullArgumentException(LocalizedFormats.FUNCTION);
            }
            if (q <= 0)
            {
                throw new NotStrictlyPositiveException(q);
            }
            if (maximumIterations <= 0)
            {
                throw new NotStrictlyPositiveException(LocalizedFormats.INVALID_MAX_ITERATIONS, maximumIterations);
            }
            VerifySequence(lowerBound, initial, upperBound);

            // initialize the recurrence
            double a     = initial;
            double b     = initial;
            double fa    = double.NaN;
            double fb    = double.NaN;
            double delta = 0;

            for (int numIterations = 0; (numIterations < maximumIterations) && (a > lowerBound || b < upperBound); ++numIterations)
            {
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final double previousA = a;
                double previousA = a;
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final double previousFa = fa;
                double previousFa = fa;
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final double previousB = b;
                double previousB = b;
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final double previousFb = fb;
                double previousFb = fb;

                delta = r * delta + q;
                a     = FastMath.Max(initial - delta, lowerBound);
                b     = FastMath.Min(initial + delta, upperBound);
                fa    = function.Value(a);
                fb    = function.Value(b);

                if (numIterations == 0)
                {
                    // at first iteration, we don't have a previous interval
                    // we simply compare both sides of the initial interval
                    if (fa * fb <= 0)
                    {
                        // the first interval already brackets a root
                        return(new double[] { a, b });
                    }
                }
                else
                {
                    // we have a previous interval with constant sign and expand it,
                    // we expect sign changes to occur at boundaries
                    if (fa * previousFa <= 0)
                    {
                        // sign change detected at near lower bound
                        return(new double[] { a, previousA });
                    }
                    else if (fb * previousFb <= 0)
                    {
                        // sign change detected at near upper bound
                        return(new double[] { previousB, b });
                    }
                }
            }

            // no bracketing found
            throw new NoBracketingException(a, b, fa, fb);
        }
Example #4
0
        public override bool OnTouchEvent(MotionEvent e)
        {
            if (_coordinatorListener == null)
            {
                return(base.OnTouchEvent(e));
            }

            int x = (int)e.RawX;
            int y = (int)e.RawY;

            switch (e.Action)
            {
            case MotionEventActions.Down:
                _downPositionY = e.RawY;
                break;

            case MotionEventActions.Move:
                int deltaY = (int)(_downPositionY - y);
                if (IsScrollTop(e) ? _coordinatorListener.OnCoordinateScroll(x, y, 0, deltaY + Math.Abs(_dragDistanceY), true) : _coordinatorListener.OnCoordinateScroll(x, y, 0, deltaY, IsScrollTop(e)))
                {
                    return(true);
                }
                break;

            case MotionEventActions.Cancel:
            case MotionEventActions.Up:
                _scrollTop = false;
                if (_coordinatorListener.IsBeingDragged)
                {
                    _coordinatorListener.OnSwitch();
                    return(true);
                }
                break;
            }
            return(base.OnTouchEvent(e));
        }
Example #5
0
 public void GoldenRatio()
 {
     Assert.Equal(1.61803398875, NMath.Round(Numbers.GoldenRatio(), 11));
 }
Example #6
0
        public void CreateRegular(int p, double q)
        {
            Segments.Clear();
            List <Vector3D> points = new List <Vector3D>();

            Geometry g            = Geometry2D.GetGeometry(p, q);
            double   circumRadius = Geometry2D.GetNormalizedCircumRadius(p, q);

            double angle = 0;

            for (int i = 0; i < p; i++)
            {
                Vector3D point = new Vector3D();
                point.X = (circumRadius * Math.Cos(angle));
                point.Y = (circumRadius * Math.Sin(angle));
                points.Add(point);
                angle += Utils.DegreesToRadians(360.0 / p);
            }

            // Turn this into segments.
            for (int i = 0; i < points.Count; i++)
            {
                int     idx1       = i;
                int     idx2       = i == points.Count - 1 ? 0 : i + 1;
                Segment newSegment = new Segment();
                newSegment.P1 = points[idx1];
                newSegment.P2 = points[idx2];

                if (g != Geometry.Euclidean)
                {
                    newSegment.Type = SegmentType.Arc;

                    if (2 == p)
                    {
                        // Our magic formula below breaks down for digons.
                        double factor = Math.Tan(Math.PI / 6);
                        newSegment.Center = newSegment.P1.X > 0 ?
                                            new Vector3D(0, -circumRadius, 0) * factor :
                                            new Vector3D(0, circumRadius, 0) * factor;
                    }
                    else
                    {
                        // Our segments are arcs in Non-Euclidean geometries.
                        // Magically, the same formula turned out to work for both.
                        // (Maybe this is because the Poincare Disc model of the
                        // hyperbolic plane is stereographic projection as well).

                        double piq    = q == -1 ? 0 : Math.PI / q;                      // Handle q infinite.
                        double t1     = Math.PI / p;
                        double t2     = Math.PI / 2 - piq - t1;
                        double factor = (Math.Tan(t1) / Math.Tan(t2) + 1) / 2;
                        newSegment.Center = (newSegment.P1 + newSegment.P2) * factor;
                    }

                    newSegment.Clockwise = Geometry.Spherical == g ? false : true;
                }

                // XXX - Make this configurable?
                // This is the color of cell boundary lines.
                //newSegment.m_color = CColor( 1, 1, 0, 1 );
                Segments.Add(newSegment);
            }
        }
Example #7
0
        public virtual string[][] GetSegments()
        {
            IList <string[]> segments = new List <string[]>();
            int segmentLimit          = factory.GetTarget().GetSerializedATNSegmentLimit();

            for (int i = 0; i < serialized.Count; i += segmentLimit)
            {
                IList <string> currentSegment = new System.ArraySegment <string>(serialized.ToArray(), i, Math.Min(i + segmentLimit, serialized.Count) - i);
                segments.Add(currentSegment.ToArray());
            }

            return(segments.ToArray());
        }
Example #8
0
 public static double Smoothed(double frac, double max)
 {
     return((max / 2.0) * (-Math.Cos(Math.PI * frac) + 1));
 }
Example #9
0
        /// <summary>
        /// Find a real root in the given interval.
        /// </summary>
        /// <param name="min"> Lower bound for the interval. </param>
        /// <param name="max"> Upper bound for the interval. </param>
        /// <param name="fMin"> function value at the lower bound. </param>
        /// <param name="fMax"> function value at the upper bound. </param>
        /// <returns> the point at which the function value is zero. </returns>
        /// <exception cref="TooManyEvaluationsException"> if the allowed number of calls to
        /// the function to be solved has been exhausted. </exception>
        private double Solve(double min, double max, double fMin, double fMax)
        {
            double relativeAccuracy      = this.RelativeAccuracy;
            double absoluteAccuracy      = this.AbsoluteAccuracy;
            double functionValueAccuracy = this.FunctionValueAccuracy;

            // [x0, x2] is the bracketing interval in each iteration
            // x1 is the last approximation and an interpolation point in (x0, x2)
            // x is the new root approximation and new x1 for next round
            // d01, d12, d012 are divided differences

            double x0 = min;
            double y0 = fMin;
            double x2 = max;
            double y2 = fMax;
            double x1 = 0.5 * (x0 + x2);
            double y1 = this.ComputeObjectiveValue(x1);

            double oldx = double.PositiveInfinity;

            while (true)
            {
                // Muller's method employs quadratic interpolation through
                // x0, x1, x2 and x is the zero of the interpolating parabola.
                // Due to bracketing condition, this parabola must have two
                // real roots and we choose one in [x0, x2] to be x.
                double d01    = (y1 - y0) / (x1 - x0);
                double d12    = (y2 - y1) / (x2 - x1);
                double d012   = (d12 - d01) / (x2 - x0);
                double c1     = d01 + (x1 - x0) * d012;
                double delta  = c1 * c1 - 4 * y1 * d012;
                double xplus  = x1 + (-2.0 * y1) / (c1 + FastMath.Sqrt(delta));
                double xminus = x1 + (-2.0 * y1) / (c1 - FastMath.Sqrt(delta));
                // xplus and xminus are two roots of parabola and at least
                // one of them should lie in (x0, x2)
                double x = this.IsSequence(x0, xplus, x2) ? xplus : xminus;
                double y = this.ComputeObjectiveValue(x);

                // check for convergence
                double tolerance = FastMath.Max(relativeAccuracy * FastMath.Abs(x), absoluteAccuracy);
                if (FastMath.Abs(x - oldx) <= tolerance || FastMath.Abs(y) <= functionValueAccuracy)
                {
                    return(x);
                }

                // Bisect if convergence is too slow. Bisection would waste
                // our calculation of x, hopefully it won't happen often.
                // the real number equality test x == x1 is intentional and
                // completes the proximity tests above it
                bool bisect = (x <x1 && (x1 - x0)> 0.95 * (x2 - x0)) || (x > x1 && (x2 - x1) > 0.95 * (x2 - x0)) || (x == x1);
                // prepare the new bracketing interval for next iteration
                if (!bisect)
                {
                    x0   = x < x1 ? x0 : x1;
                    y0   = x < x1 ? y0 : y1;
                    x2   = x > x1 ? x2 : x1;
                    y2   = x > x1 ? y2 : y1;
                    x1   = x;
                    y1   = y;
                    oldx = x;
                }
                else
                {
                    double xm = 0.5 * (x0 + x2);
                    double ym = this.ComputeObjectiveValue(xm);
                    if (MyUtils.Signum(y0) + MyUtils.Signum(ym) == 0.0)
                    {
                        x2 = xm;
                        y2 = ym;
                    }
                    else
                    {
                        x0 = xm;
                        y0 = ym;
                    }
                    x1   = 0.5 * (x0 + x2);
                    y1   = this.ComputeObjectiveValue(x1);
                    oldx = double.PositiveInfinity;
                }
            }
        }
Example #10
0
        private static Rectangle GetBoundingRectangle(Vector2 tl, Vector2 tr, Vector2 bl, Vector2 br)
        {
            // Find the minimum and maximum "corners" based on the given vectors
            float minX  = MathF.Min(tl.X, MathF.Min(tr.X, MathF.Min(bl.X, br.X)));
            float maxX  = MathF.Max(tl.X, MathF.Max(tr.X, MathF.Max(bl.X, br.X)));
            float minY  = MathF.Min(tl.Y, MathF.Min(tr.Y, MathF.Min(bl.Y, br.Y)));
            float maxY  = MathF.Max(tl.Y, MathF.Max(tr.Y, MathF.Max(bl.Y, br.Y)));
            float sizeX = maxX - minX + .5F;
            float sizeY = maxY - minY + .5F;

            return(new Rectangle((int)(MathF.Ceiling(minX) - .5F), (int)(MathF.Ceiling(minY) - .5F), (int)MathF.Floor(sizeX), (int)MathF.Floor(sizeY)));
        }