示例#1
0
        /// <summary>
        ///     Computes the error function for x. Adopted from http://www.johndcook.com/cpp_erf.html
        /// </summary>
        /// <param name="x"></param>
        /// <returns></returns>
        public static double Erf(double x)
        {
            // constants
            double a1 = 0.254829592;
            double a2 = -0.284496736;
            double a3 = 1.421413741;
            double a4 = -1.453152027;
            double a5 = 1.061405429;
            double p  = 0.3275911;

            // Save the sign of x
            int sign = 1;

            if (x < 0)
            {
                sign = -1;
            }
            x = M.Abs(x);

            // A&S formula 7.1.26
            double t = 1.0 / (1.0 + p * x);
            double y = 1.0 - (((((a5 * t + a4) * t) + a3) * t + a2) * t + a1) * t * M.Exp(-x * x);

            return(sign * y);
        }
示例#2
0
        public static float LinearInterpolate(Vector2 position, MapData[,] map, ScalarFieldType fieldType)
        {
            float x  = position.X;
            float y  = position.Y;
            float x1 = (int)MathFunctions.Clamp((float)Math.Ceiling(x), 0, map.GetLength(0) - 2);
            float y1 = (int)MathFunctions.Clamp((float)Math.Ceiling(y), 0, map.GetLength(1) - 2);
            float x2 = (int)MathFunctions.Clamp((float)Math.Floor(x), 0, map.GetLength(0) - 2);
            float y2 = (int)MathFunctions.Clamp((float)Math.Floor(y), 0, map.GetLength(1) - 2);

            if (Math.Abs(x1 - x2) < 0.5f)
            {
                x1 = x1 + 1;
            }

            if (Math.Abs(y1 - y2) < 0.5f)
            {
                y1 = y1 + 1;
            }


            float q11 = map[(int)x1, (int)y1].GetValue(fieldType);
            float q12 = map[(int)x1, (int)y2].GetValue(fieldType);
            float q21 = map[(int)x2, (int)y1].GetValue(fieldType);
            float q22 = map[(int)x2, (int)y2].GetValue(fieldType);

            return(MathFunctions.LinearCombination(x, y, x1, y1, x2, y2, q11, q12, q21, q22));
        }
示例#3
0
        /// <summary>
        ///     Resuelve el parametro de la clotoide dado los radios <c>r0</c> y <c>r1</c> Con una distancia <c>d</c> entre los
        ///     puntos.
        /// </summary>
        private static double SolveParam(double d, double r0, double r1)
        {
            Func <double, double> f = (a) =>
            {
                double fs0, fc0;
                ClothoUtils.Fresnel(a / (r0 * sqrtpi), out fs0, out fc0);

                double fs1, fc1;
                ClothoUtils.Fresnel(a / (r1 * sqrtpi), out fs1, out fc1);

                double fc10 = (fc1 - fc0);
                double fs10 = (fs1 - fs0);

                return(a * a * SysMath.PI * (fc10 * fc10 + fs10 * fs10) - d * d);
            };

            int maxEval = 50; // 30

            try
            {
                double min = 0;
                double max = SysMath.Min(SysMath.Abs(r0), SysMath.Abs(r1)) * ClothoUtils.MAX_L;
                double v   = Solver.Solve(f, min, max, Solver.Type.BrentSolver, DEFAULT_ABSOLUTE_ACCURACY, maxEval);
                return(v);
            }
            catch (Exception e)
            {
                Debug.WriteLine(e);
                throw;
            }
        }
示例#4
0
 //
 // After rotating, the matrix needs to be translated. This function finds the area of image
 // which was previously centered and adjusts translations so that is again the center, post-rotation.
 // @param axis Matrix.MTRANS_X or Matrix.MTRANS_Y
 // @param trans the value of trans in that axis before the rotation
 // @param prevImageSize the width/height of the image before the rotation
 // @param imageSize width/height of the image after rotation
 // @param prevViewSize width/height of view before rotation
 // @param viewSize width/height of view after rotation
 // @param drawableSize width/height of drawable
 //
 private void TranslateMatrixAfterRotate(int axis, float trans, float prevImageSize, float imageSize, int prevViewSize, int viewSize, int drawableSize)
 {
     if (imageSize < viewSize)
     {
         //
         // The width/height of image is less than the view's width/height. Center it.
         //
         _m[axis] = (viewSize - (drawableSize * _m[Matrix.MscaleX])) * 0.5f;
     }
     else if (trans > 0)
     {
         //
         // The image is larger than the view, but was not before rotation. Center it.
         //
         _m[axis] = -((imageSize - viewSize) * 0.5f);
     }
     else
     {
         //
         // Find the area of the image which was previously centered in the view. Determine its distance
         // from the left/top side of the view as a fraction of the entire image's width/height. Use that percentage
         // to calculate the trans in the new view width/height.
         //
         var percentage = (Math.Abs(trans) + (0.5f * prevViewSize)) / prevImageSize;
         _m[axis] = -((percentage * imageSize) - (viewSize * 0.5f));
     }
 }
示例#5
0
 /// <summary>
 /// Indicates whether the current object is equal to another object of the same type.
 /// </summary>
 /// <param name="other">An object to compare with this object.</param>
 /// <returns>true if the current object is equal to the <paramref name="other" /> parameter; otherwise, false.</returns>
 public bool Equals(Offset other)
 {
     return((NMath.Abs(I.X - other.I.X) < Tolerance) &&
            (NMath.Abs(I.Y - other.I.Y) < Tolerance) &&
            (NMath.Abs(J.X - other.J.X) < Tolerance) &&
            (NMath.Abs(J.Y - other.J.Y) < Tolerance));
 }
示例#6
0
 /// <summary>
 /// Multiplies the Color's Saturation, and Luminance or Brightness by the arguments;
 /// and optionally specifies the output Alpha.
 /// </summary>
 /// <param name="color">The color to transform.</param>
 /// <param name="colorTransformMode">Transform mode.</param>
 /// <param name="saturationTransform">The transformation multiplier.</param>
 /// <param name="brightnessTransform">The transformation multiplier.</param>
 /// <param name="outputAlpha">Can optionally specify the Alpha to directly
 /// set on the output. If null, then the input <paramref name="color"/>
 /// Alpha is used.</param>
 /// <returns>RGB Color.</returns>
 public static Color TransformSaturationAndValue(
     Color color,
     ColorTransformMode colorTransformMode,
     double saturationTransform,
     double brightnessTransform,
     byte?outputAlpha = null)
 {
     double[] hsl = colorTransformMode == ColorTransformMode.Hsl
                                 ? SimpleColorTransforms.RgbToHsl(color)
                                 : SimpleColorTransforms.RgbToHsb(color);
     if ((SystemMath.Abs(hsl[1]) < SimpleColorTransforms.tolerance) &&
         (saturationTransform > 1D))
     {
         hsl[1] = saturationTransform - 1D;
     }
     else
     {
         hsl[1] *= saturationTransform;
     }
     if ((SystemMath.Abs(hsl[2]) < SimpleColorTransforms.tolerance) &&
         (brightnessTransform > 1D))
     {
         hsl[2] = brightnessTransform - 1D;
     }
     else
     {
         hsl[2] *= brightnessTransform;
     }
     return(colorTransformMode == ColorTransformMode.Hsl
                                 ? SimpleColorTransforms.HslToRgb(hsl[0], hsl[1], hsl[2], outputAlpha ?? color.A)
                                 : SimpleColorTransforms.HsbToRgb(hsl[0], hsl[1], hsl[2], outputAlpha ?? color.A));
 }
示例#7
0
        /// <summary>
        ///   Computes the new motor velocity based on the current velocity, such that the velocity always moves towards
        ///   the set point (if regulation is active), or the acceleration curve dictated by the <see cref="Acceleration" />
        ///   property.
        ///   The magnitude of the returned speed will never be greater than <see cref="StepperMotor.MaximumSpeed" /> which in turn
        ///   can never
        ///   exceed <see cref="StepperMotor.MaximumPossibleSpeed" />.
        ///   <see cref="StepperMotor.MaximumSpeed" />.
        /// </summary>
        /// <returns>The computed velocity, in steps per second.</returns>
        /// <remarks>
        ///   A positive value indicates speed in the forward direction, while a negative value indicates speed in the reverse
        ///   direction.
        ///   'forward' is defined as motion towards a higher position value; 'reverse' is defined as motion towards a lower
        ///   position value.
        ///   No attempt is made here to define the mechanical direction. A speed value that is within
        ///   <see cref="StepperMotor.MotorStoppedThreshold" />
        ///   of zero is considered to mean that the motor should be stopped.
        /// </remarks>
        double ComputeAcceleratedVelocity()
        {
            var distanceToGo     = ComputeDistanceToTarget();
            var absoluteDistance = Math.Abs(distanceToGo);
            var direction        = Math.Sign(distanceToGo);

            if (distanceToGo == 0)
            {
                return(0.0); // We're there.
            }
            if (!IsMoving)
            {
                return(Math.Sqrt(2.0 * Acceleration) * direction); // Accelerate away from stop.
            }
            // Compute the unconstrained target speed based on the deceleration curve or the regulation set point.
            var targetSpeed = regulating ? speedSetpoint : Math.Sqrt(2.0 * absoluteDistance * Acceleration) * direction;
            // The change in speed is a function of the absolute current speed and acceleration.
            var increment         = Acceleration / Math.Abs(motorSpeed);
            var directionOfChange = Math.Sign(targetSpeed - motorSpeed);
            var newSpeed          = motorSpeed + increment * directionOfChange;
            // The computed new speed must be constrained by both the MaximumSpeed and the acceleration curve.
            var clippedSpeed = newSpeed.ConstrainToLimits(-maximumSpeed, +maximumSpeed);

            return(clippedSpeed);
        }
示例#8
0
        public void CalculateStep(int numberOfSegments)
        {
            var set = new HashSet <OptimizationParameter>
            {
                new OptimizationStepParameter("ema-fast", 1, 100),
                new OptimizationStepParameter("ema-slow", -10, -10),
                new OptimizationStepParameter("ema-custom", -100, -1)
            };

            _strategy.Initialize(
                new Target("Profit", new Maximization(), null),
                new List <Constraint>(),
                set,
                new StepBaseOptimizationStrategySettings {
                DefaultSegmentAmount = numberOfSegments
            });

            foreach (var parameter in set)
            {
                var stepParameter = parameter as OptimizationStepParameter;
                Assert.NotNull(stepParameter);
                var actual = Math.Abs(stepParameter.MaxValue - stepParameter.MinValue) /
                             numberOfSegments;
                Assert.AreEqual(actual, stepParameter.Step);
                Assert.AreEqual(actual / 10, stepParameter.MinStep);
            }
        }
示例#9
0
        /// <summary>
        /// Reads all of the formations and returns a list of objects with data.
        /// </summary>
        /// <param name="excel">The excel application.</param>
        /// <returns>List&lt;DBLocation&gt;.</returns>
        private static List <FormationMatcher> ReadFormations(ExcelFile excel)
        {
            List <FormationMatcher> locations = new List <FormationMatcher>();
            List <string>           areas     = excel.RangeValuesBelowHeader("AreaChild");
            List <string>           names     = excel.RangeValuesBelowHeader("Formation");
            int           numberOfRows        = names.Count;
            List <string> latitudes           = excel.RangeValuesBelowHeader("Latitude", includeNull: true, numberOfRows: numberOfRows);
            List <string> longitudes          = excel.RangeValuesBelowHeader("Longitude", includeNull: true, numberOfRows: numberOfRows);
            List <string> otherNames          = excel.RangeValuesBelowHeader("SubFormation", includeNull: true, numberOfRows: numberOfRows);

            for (int i = 0, length = names.Count; i < length; i++)
            {
                double longitude;
                if (!double.TryParse(longitudes[i], out longitude))
                {
                    longitude = 0;
                }
                double latitude;
                if (!double.TryParse(latitudes[i], out latitude))
                {
                    latitude = 0;
                }
                if (!(NMath.Abs(longitude) < 1) ||
                    !(NMath.Abs(latitude) < 1))
                {
                    continue;
                }
                FormationMatcher location = new FormationMatcher(areas[i], names[i], otherNames[i]);
                locations.Add(location);
            }
            return(locations);
        }
示例#10
0
        public static bool GetMeas(OSat sat, out double p1, out double p2, out double l1, out double l2, out double dp1)
        {
            dp1 = Common.DELTA_P1;
            p1  = p2 = l1 = l2 = 0d;
            if (sat is null || sat.SatData.Count <= 0)
            {
                return(false);
            }

            p1 = sat["P1"];
            p2 = sat["P2"];
            l1 = sat["L1"];
            l2 = sat["L2"];
            if (p1 == 0d)
            {
                p1  = sat["C1"];
                dp1 = Common.DELTA_C1;
            }

            if (Math.Abs(l1) < 1e-3 ||
                Math.Abs(l2) < 1e-3 ||
                Math.Abs(p1) < 1e-3 ||
                Math.Abs(p2) < 1e-3)
            {
                return(false);
            }
            return(true);
        }
示例#11
0
        public static Plane Normalize(Plane value)
        {
            const float FLT_EPSILON = 1.192092896e-07f; // smallest such that 1.0+FLT_EPSILON != 1.0

            Plane result;

            float f = value.Normal.X * value.Normal.X + value.Normal.Y * value.Normal.Y + value.Normal.Z * value.Normal.Z;

            if (SM.Abs(f - 1.0f) < FLT_EPSILON)
            {
                result.Normal = value.Normal;
                result.D      = value.D;
                return(result); // It already normalized, so we don't need to farther process.
            }

            float fInv = 1.0f / (float)SM.Sqrt(f);

            result.Normal.X = value.Normal.X * fInv;
            result.Normal.Y = value.Normal.Y * fInv;
            result.Normal.Z = value.Normal.Z * fInv;

            result.D = value.D * fInv;

            return(result);
        }
        /// <summary>
        /// Returns the 3 'x' solutions to the equation x^3 + a2*x^2 + a1*x + a0 = 0.
        /// </summary>
        /// <param name="a0">Constant.</param>
        /// <param name="a1">Multiplier to x.</param>
        /// <param name="a2">Multiplier to x^2.</param>
        /// <param name="returnFirstRoot">if set to <c>true</c> [return first root].</param>
        /// <returns>System.Double[].</returns>
        private static double[] cubicCurveRootsNormalized(double a0, double a1, double a2, bool returnFirstRoot = false)
        {
            double Q         = (3 * a1 - a2.Squared()) / 9d;
            double R         = (9 * a2 * a1 - 27 * a0 - 2 * a2.Cubed()) / 54d;
            double D         = Q.Cubed() + R.Squared();
            double aCosRatio = R / Numbers.Sqrt(NMath.Abs(-Q.Cubed()));
            double x1;

            if ((returnFirstRoot && D.IsGreaterThanOrEqualTo(0)) ||
                (aCosRatio.IsLessThan(-1) || aCosRatio.IsGreaterThan(1)))
            {
                double S = Numbers.CubeRoot(R + Numbers.Sqrt(D));
                double T = Numbers.CubeRoot(R - Numbers.Sqrt(D));
                x1 = (S + T) - (1 / 3d) * a2;

                return(new double[] { x1 });
            }

            double theta = NMath.Acos(aCosRatio);

            x1 = 2 * Numbers.Sqrt((NMath.Abs(-Q))) * NMath.Cos(theta / 3d) - a2 / 3d;
            double x2 = 2 * Numbers.Sqrt(NMath.Abs(-Q)) * NMath.Cos((theta + 2 * Numbers.Pi) / 3d) - a2 / 3d;
            double x3 = 2 * Numbers.Sqrt(NMath.Abs(-Q)) * NMath.Cos((theta + 4 * Numbers.Pi) / 3d) - a2 / 3d;

            return(new double[] { x1, x2, x3 });
        }
        /// <summary>
        ///   Moves the motor at a regulated speed, using acceleration whenever the speed changes.
        ///   Once moving, the speed may be changed by calling this method again with the new value.
        ///   To decelerate to a stop, call this method with a speed of 0.
        /// </summary>
        /// <param name="speed">The target speed.</param>
        /// <exception cref="System.ArgumentOutOfRangeException">
        ///   speed;speed must be in the range -MaximumPossibleSpeed to
        ///   +MaximumPossibleSpeed
        /// </exception>
        public void MoveAtRegulatedSpeed(double speed)
        {
            var absoluteSpeed = Math.Abs(speed);

            if (absoluteSpeed > MaximumPossibleSpeed)
            {
                throw new ArgumentOutOfRangeException("speed",
                                                      "speed must be in the range -MaximumPossibleSpeed to +MaximumPossibleSpeed");
            }
            //if (maximumSpeed < absoluteSpeed)
            //    maximumSpeed = absoluteSpeed;

            // Set the target position, effectively, infinitely far away so we will never stop.
            targetPosition = speed >= 0 ? int.MaxValue : int.MinValue;
            speedSetpoint  = absoluteSpeed < MotorStoppedThreshold ? 0.0 : speed;
            var direction = (short)Math.Sign(targetPosition - currentPosition);

            lock (motorUpdateLock)
            {
                regulating = true;
                if (!IsMoving)
                {
                    StartStepping(direction);
                }
            }
        }
示例#14
0
        public object GetCurrentValue(Brush defaultOriginValue,
                                      Brush defaultDestinationValue,
                                      AnimationClock animationClock)
        {
            if (!animationClock.CurrentProgress.HasValue)
            {
                return(Brushes.Transparent);
            }

            // use the standard values if From and To are not set
            // it is the value of the given property
            defaultOriginValue      = From ?? defaultOriginValue;
            defaultDestinationValue = To ?? defaultDestinationValue;

            if (Math.Abs(animationClock.CurrentProgress.Value - 0) < 1e-5)
            {
                return(defaultOriginValue);
            }
            if (Math.Abs(animationClock.CurrentProgress.Value - 1) < 1e-5)
            {
                return(defaultDestinationValue);
            }

            return(new VisualBrush(new Border()
            {
                Width = 1,
                Height = 1,
                Background = defaultOriginValue,
                Child = new Border()
                {
                    Background = defaultDestinationValue,
                    Opacity = animationClock.CurrentProgress.Value
                }
            }));
        }
示例#15
0
        public override void SetOutputPowerAndPolarity(double duty)
        {
            bool polarity = duty >= 0.0;

            SetOutputPowerAndPolarity(Math.Abs(duty), polarity);
            base.SetOutputPowerAndPolarity(duty);
        }
示例#16
0
    private void setMouseCorner()
    {
        //var xSlope:double = (WIDTH / HEIGHT) * mouseY;
        //var ySlope:double = HEIGHT - (HEIGHT / WIDTH) * mouseX;
        double x      = mouseX - (WIDTH - HEIGHT) * 0.5;
        double y      = mouseY;
        double xSlope = y;
        double ySlope = HEIGHT - x;

        if (x > xSlope && y > ySlope)
        {
            mouseCorner = Room.RIGHT;
        }
        else if (x > xSlope && y < ySlope)
        {
            mouseCorner = Room.UP;
        }
        else if (x < xSlope && y > ySlope)
        {
            mouseCorner = Room.DOWN;
        }
        else if (x < xSlope && y < ySlope)
        {
            mouseCorner = Room.LEFT;
        }
        if (Math.Abs(mouseX - WIDTH * 0.5) < SCALE * 0.75 && Math.Abs(mouseY - HEIGHT * 0.5) < SCALE * 0.75)
        {
            mouseCorner = 0;
        }
    }
示例#17
0
        public Move ComputeMove(Position dest)
        {
            var move = new Move
            {
                Pos = new Position
                {
                    X = dest.X - this.Speed.Vx,
                    Y = dest.Y - this.Speed.Vy
                }
            };

            // Acc
            var dist = this.Pos.Dist(move.Pos);

            if (Math.Abs(dist) <= 0.0001)
            {
                return(move);
            }

            //var expectedVx = Math.Abs(move.Pos.X - this.Pos.X) / (1 - this.Friction);
            //var expectedVy = Math.Abs(move.Pos.Y - this.Pos.Y) / (1 - this.Friction);

            //var accX = (int)Math.Round(expectedVx * dist * this.Mass);
            //var accY = (int)Math.Round(expectedVy * dist * this.Mass);

            //Program.ConsoleHelper.Debug($"accX={accX}|accY={accY}");
            //move.Acc = Math.Min((accX + accY) / 2, 300);

            var acc = (int)Math.Round(this.Mass * dist);

            move.Acc = Math.Min(acc, 300);
            return(move);
        }
示例#18
0
        public static Quaternion Slerp(Quaternion p, Quaternion q, float time, bool useShortCut = false)
        {
            var cos = p.Dot(q);

            var angle = MathDotNet.Acos(cos);

            if (MathDotNet.Abs(angle) < Quaternion.EPSILONE)
            {
                return(p);
            }

            var sin = MathDotNet.Sin(angle);

            var inverseSin = 1f / sin;

            var coeff0 = MathDotNet.Sin((1f - time) * angle) * inverseSin;
            var coeff1 = MathDotNet.Sin(time * angle) * inverseSin;

            if (useShortCut == false || cos >= 0d)
            {
                return(p * coeff0 + q * coeff1);
            }

            coeff0 = -coeff0;

            Quaternion temp = p * coeff0 + q * coeff1;

            var factor = 1d / MathDotNet.Sqrt(temp.Normalized);

            return(temp * factor);
        }
        public void DrawFade(View content, Canvas canvas, float openPercent)
        {
            if (!FadeEnabled)
            {
                return;
            }

            var alpha = (int)(FadeDegree * 255 * Math.Abs(1 - openPercent));

            _fadePaint.Color = Color.Argb(alpha, 0, 0, 0);
            var left  = 0;
            var right = 0;

            switch (Mode)
            {
            case MenuMode.Left:
                left  = content.Left - BehindWidth;
                right = content.Left;
                break;

            case MenuMode.Right:
                left  = content.Right;
                right = content.Right + BehindWidth;
                break;

            case MenuMode.LeftRight:
                left  = content.Left - BehindWidth;
                right = content.Left;
                canvas.DrawRect(left, 0, right, Height, _fadePaint);
                left  = content.Right;
                right = content.Right + BehindWidth;
                break;
            }
            canvas.DrawRect(left, 0, right, Height, _fadePaint);
        }
示例#20
0
        /// <summary>
        /// Find the expected exposure
        /// </summary>
        /// <param name="mtm"></param>
        /// <param name="pce"></param>
        /// <param name="expExp"></param>
        /// <param name="expExp2"></param>
        public static void Exposures(double mtm,
                                     double pce,
                                     out double expExp,
                                     out double expExp2)
        {
            //**** Step 2 - Find the Cumulative Normal Probability
            //**** CDF=1-NORMDIST(-MTM/PCE,0,1,TRUE)
            //**** Step 3 - Find the marginal Normal Probability
            //**** PDF=NORMDIST(-MTM/PCE,0,1,FALSE)
            //****

            double cumulativeNormal = 1.0;
            double normalDensity    = 0.0;

            if (Math.Abs(pce) > 1E-07)
            {
                normalDensity    = NormalDistribution.Ndf(-mtm / pce);                                //use normal dist
                cumulativeNormal = 1.0 - new NormalDistribution().CumulativeDistribution(-mtm / pce); //use cum normal dist
            }

            //**** Step 4 - Find the expected exposure for the FX fwd
            //**** MTM*CDF+PCE*PDF
            //****
            expExp  = mtm * cumulativeNormal + pce * normalDensity;
            expExp2 = (Math.Pow(mtm, 2) + Math.Pow(pce, 2)) * cumulativeNormal + mtm * pce * normalDensity;
        }
示例#21
0
        public static List <Vector3Int> MakeLine(Vector3Int pos1, Vector3Int pos2)
        {
            List <Vector3Int> affected = new List <Vector3Int>();
            bool notdrawn = true;

            int x1   = pos1.x;
            int y1   = pos1.x;
            int z1   = pos1.x;
            int x2   = pos2.x;
            int y2   = pos2.y;
            int z2   = pos2.z;
            int tipx = x1;
            int tipy = y1;
            int tipz = z1;
            int dx   = Math.Abs(x2 - x1);
            int dy   = Math.Abs(y2 - y1);
            int dz   = Math.Abs(z2 - z1);

            if (dx + dy + dz == 0)
            {
                affected.Add(pos2 + new Vector3Int(tipx, tipy, tipz));
                notdrawn = false;
            }

            if (Math.Max(Math.Max(dx, dy), dz) == dx && notdrawn)
            {
                for (int domstep = 0; domstep <= dx; domstep++)
                {
                    tipx = x1 + domstep * (x2 - x1 > 0 ? 1 : -1);
                    tipy = (int)Math.Round(y1 + domstep * (((double)dy) / ((double)dx)) * (y2 - y1 > 0 ? 1 : -1));
                    tipz = (int)Math.Round(z1 + domstep * (((double)dz) / ((double)dx)) * (z2 - z1 > 0 ? 1 : -1));
                    affected.Add(new Vector3Int(tipx, tipy, tipz));
                }
                notdrawn = false;
            }

            if (Math.Max(Math.Max(dx, dy), dz) == dy && notdrawn)
            {
                for (int domstep = 0; domstep <= dx; domstep++)
                {
                    tipx = x1 + domstep * (x2 - x1 > 0 ? 1 : -1);
                    tipy = (int)Math.Round(y1 + domstep * ((double)dy) / ((double)dx) * (y2 - y1 > 0 ? 1 : -1));
                    tipz = (int)Math.Round(z1 + domstep * ((double)dz) / ((double)dx) * (z2 - z1 > 0 ? 1 : -1));
                    affected.Add(new Vector3Int(tipx, tipy, tipz));
                }
                notdrawn = false;
            }

            if (Math.Max(Math.Max(dx, dy), dz) == dz && notdrawn)
            {
                for (int domstep = 0; domstep <= dz; domstep++)
                {
                    tipz = z1 + domstep * (z2 - z1 > 0 ? 1 : -1);
                    tipy = (int)Math.Round(y1 + domstep * ((double)dy) / ((double)dz) * (y2 - y1 > 0 ? 1 : -1));
                    tipx = (int)Math.Round(x1 + domstep * ((double)dx) / ((double)dz) * (x2 - x1 > 0 ? 1 : -1));
                    affected.Add(pos2 + new Vector3Int(tipx, tipy, tipz));
                }
            }
            return(affected);
        }
示例#22
0
        public ClothoidArc2(double l0,
                            Vector2d point0, Vector2d point1,
                            double radius0, double radius1)
        {
            // Correccion sobre los radios.
            if (SysMath.Sign(radius1) != SysMath.Sign(radius0))
            {
                if (double.IsInfinity(radius0))
                {
                    radius0 = SysMath.Sign(radius1) * double.PositiveInfinity;
                }
                else if (double.IsInfinity(radius1))
                {
                    radius1 = SysMath.Sign(radius0) * double.PositiveInfinity;
                }
                else
                {
                    // No se permite cambio de signo en el radio. Funcionaria???
                    Contract.Assert(false);
                }
            }

            if (SysMath.Abs(radius0) > SysMath.Abs(radius1))
            {
                // t positivas
                this.InvertY = radius1 < 0;
            }
            else
            {
                // t negativa
                this.InvertY = radius1 > 0;
            }

            // Diferencia de puntos en coordenadas reales.
            Vector2d v01 = point1.Sub(point0);

            this.A = SolveParam(v01.Length, radius0, radius1);

            // Desarrollo segun el radio en el punto (0) y (1).
            double l0_n = ClothoUtils.ClothoL(radius0, this.InvertY, this.A);
            double l1_n = ClothoUtils.ClothoL(radius1, this.InvertY, this.A);

            // Coordenadas en el punto (0) y (1) para una clotoide normalizada.
            Point2d p0_n = ClothoUtils.Clotho(l0_n, this.InvertY, this.A);
            Point2d p1_n = ClothoUtils.Clotho(l1_n, this.InvertY, this.A);

            Vector2d v01_n = p1_n.Sub(p0_n);

            // Rotacion de v01_n -> v01.
            double r = v01_n.AngleTo(v01);

            // Transformacion a aplicar.
            this.transform = Transform2.Translate(point1.X - p1_n.X, point1.Y - p1_n.Y)
                             .Concat(Transform2.Rotate(p1_n.X, p1_n.Y, r));

            this.l0 = l0_n;
            this.l1 = l1_n;

            this.SetTInterval(l0, l0 + (this.l1 - this.l0));
        }
示例#23
0
        public static double SolveParam_2(double len, double r1, double r2)
        {
            Func <double, double> f = (a) =>
            {
                double fs1, fc1;
                FresnelUtils.Fresnel(a / (r1 * sqrtpi), out fs1, out fc1);

                double fs2, fc2;
                FresnelUtils.Fresnel(a / (r2 * sqrtpi), out fs2, out fc2);

                double fc21 = (fc2 - fc1);
                double fs21 = (fs2 - fs1);

                return(a * a * SysMath.PI * (fc21 * fc21 + fs21 * fs21) - len * len);
            };

            int maxEval = 50; // 30

            try
            {
                double min = 0;
                double max = SysMath.Min(SysMath.Abs(r1), SysMath.Abs(r2)) * MAX_L;
                return(Solver.Solve(f, min, max, Solver.Type.Brent, Solver.DEFAULT_ABSOLUTE_ACCURACY, maxEval));
            }
            catch (Exception e)
            {
                Debug.WriteLine(e);
                throw;
            }
        }
示例#24
0
        // d = b^2 - a * c  computed accurately enough by a tricky scheme.
        // Ported from @hkrish's polysolve.c
        private static Real GetDiscriminant(Real a, Real b, Real c)
        {
            Func <Real, Real[]> split = (v) =>
            {
                Real x  = v * 134217729;
                Real y  = v - x;
                Real hi = y + x; // Don't optimize y away!
                Real lo = v - hi;
                return(new[] { hi, lo });
            };

            Real D = b * b - a * c;
            Real E = b * b + a * c;

            if (Math.Abs(D) * 3 < E)
            {
                Real[] ad = split(a);
                Real[] bd = split(b);
                Real[] cd = split(c);
                Real   p  = b * b;
                Real   dp = (bd[0] * bd[0] - p + 2 * bd[0] * bd[1]) + bd[1] * bd[1];
                Real   q  = a * c;
                Real   dq = (ad[0] * cd[0] - q + ad[0] * cd[1] + ad[1] * cd[0]) + ad[1] * cd[1];
                D = (p - q) + (dp - dq); // Don’t omit parentheses!
            }

            return(D);
        }
        void UpdateVisibleRegion(LatLng pos)
        {
            var map = NativeMap;

            if (map == null)
            {
                return;
            }
            var projection = map.Projection;
            var width      = Control.Width;
            var height     = Control.Height;
            var ul         = projection.FromScreenLocation(new global::Android.Graphics.Point(0, 0));
            var ur         = projection.FromScreenLocation(new global::Android.Graphics.Point(width, 0));
            var ll         = projection.FromScreenLocation(new global::Android.Graphics.Point(0, height));
            var lr         = projection.FromScreenLocation(new global::Android.Graphics.Point(width, height));
            var dlat       = Math.Max(Math.Abs(ul.Latitude - lr.Latitude), Math.Abs(ur.Latitude - ll.Latitude));
            var dlong      = Math.Max(Math.Abs(ul.Longitude - lr.Longitude), Math.Abs(ur.Longitude - ll.Longitude));

            ((Map)Element).VisibleRegion = new MapSpan(
                new Position(
                    pos.Latitude,
                    pos.Longitude
                    ),
                dlat,
                dlong
                );
        }
示例#26
0
        ///<summary>
        ///</summary>
        ///<param name="optionType"></param>
        ///<param name="price"></param>
        ///<param name="strike"></param>
        ///<returns></returns>
        ///<exception cref="ArgumentOutOfRangeException"></exception>
        public static double ExercisePayoff(Type optionType, double price, double strike)
        {
            switch (optionType)
            {
            case Type.Call:
            {
                return(Math.Max(price - strike, 0.0));
            }

            case Type.Put:
            {
                return(Math.Max(strike - price, 0.0));
            }

            case Type.Straddle:
            {
                return(Math.Abs(strike - price));
            }

            default:
            {
                throw new ArgumentOutOfRangeException(nameof(optionType), optionType, "TODO: Unknown option type");
            }
            }
        }
        internal static bool LineSegmentIntersection(Vector2Double p1, Vector2Double p2, Vector2Double p3, Vector2Double p4, ref Vector2Double result)
        {
            double num1 = p2.x - p1.x;
            double num2 = p2.y - p1.y;
            double num3 = p4.x - p3.x;
            double num4 = p4.y - p3.y;
            double num5 = (num1 * num4 - num2 * num3);

            if (Math.Abs(num5) < Epsilon)
            {
                return(false);
            }

            double num6 = p3.x - p1.x;
            double num7 = p3.y - p1.y;
            double num8 = (num6 * num4 - num7 * num3) / num5;

            if (num8 < 0.0d || num8 > 1.0d)
            {
                return(false);
            }

            double num9 = (num6 * num2 - num7 * num1) / num5;

            if (num9 < 0.0d || num9 > 1.0d)
            {
                return(false);
            }

            result = new Vector2Double(p1.x + num8 * num1, p1.y + num8 * num2);

            return(true);
        }
示例#28
0
 public Main()
 {
     InitializeBot();
     InitializeComponent();
     Translate();
     InitializeLogging();
     if (nManagerSetting.CurrentSetting.ActivateAlwaysOnTopFeature)
     {
         TopMost = true;
     }
     InitializeUI();
     Logging.Status = "Startup Complete";
     using (Graphics g = CreateGraphics())
     {
         if (Math.Abs(g.DpiX - 96F) > 0.1)
         {
             Logging.Write("There is a problem with your Windows Font Size configuration.");
             Logging.Write("Please set it to 100% size or you may have problems reading TheNoobBot's forms. hint: http://www.wikihow.com/Change-Font-Size-on-a-Computer");
         }
     }
     if (nManagerSetting.AutoStartProduct && !string.IsNullOrEmpty(nManagerSetting.AutoStartProductName) && !string.IsNullOrEmpty(nManagerSetting.AutoStartProfileName))
     {
         if (!string.IsNullOrEmpty(nManagerSetting.CurrentSetting.LastProductLoaded) &&
             nManagerSetting.AutoStartProductName.ToLower() == nManagerSetting.CurrentSetting.LastProductLoaded.Split('-')[0].Trim().ToLower())
         {
             Products.ProductRemoteStart(new[] { nManagerSetting.AutoStartProfileName });
         }
     }
     else if (nManagerSetting.AutoStartProduct)
     {
         Products.ProductRemoteStart(new string[0]);
     }
 }
示例#29
0
        public ClothoidArc2(double l0,
                            Vec2d point0, Vec2d point1,
                            double radius0, double radius1,
                            double a)
        {
            // Correccion sobre los radios.
            if (SysMath.Sign(radius1) != SysMath.Sign(radius0))
            {
                if (double.IsInfinity(radius0))
                {
                    radius0 = SysMath.Sign(radius1) * double.PositiveInfinity;
                }
                else if (double.IsInfinity(radius1))
                {
                    radius1 = SysMath.Sign(radius0) * double.PositiveInfinity;
                }
                else
                {
                    // Se deja tal cual.
                    //// Se toma el radio inicio como infinito.
                    ////radius0 = SysMath.Sign(radius1) * double.PositiveInfinity;
                }
            }

            if (SysMath.Abs(radius0) > SysMath.Abs(radius1))
            { // t positivas
                this.invertY = radius1 < 0;
            }
            else
            { // t negativa
                this.invertY = radius1 > 0;
            }

            // Diferencia de puntos en coordenadas reales.
            Vec2d v01 = point1.Sub(point0);

            this.a = a;

            // Desarrollo segun el radio en el punto (0) y (1).
            double l0_n = ClothoUtils.ClothoL(radius0, this.invertY, this.a);
            double l1_n = ClothoUtils.ClothoL(radius1, this.invertY, this.a);

            // Coordenadas en el punto (0) y (1) para una clotoide normalizada.
            Vec2d p0_n = ClothoUtils.Clotho(l0_n, this.invertY, this.a);
            Vec2d p1_n = ClothoUtils.Clotho(l1_n, this.invertY, this.a);

            Vec2d v01_n = p1_n.Sub(p0_n);

            // Rotacion de v01_n -> v01.
            double r = vecMath.Angle(v01_n, v01);

            // Transformacion a aplicar.
            this.transform = Transform2.Translate(point1.X - p1_n.X, point1.Y - p1_n.Y)
                             .Mult(Transform2.Rotate(p1_n.X, p1_n.Y, r));

            this.l0 = l0_n;
            this.l1 = l1_n;

            this.SetTInterval(l0, l0 + (this.l1 - this.l0));
        }
示例#30
0
        /// <summary>
        /// Rotates the images with an optimized method when the angle is 90, 180 or 270 degrees.
        /// </summary>
        /// <param name="source">The source image.</param>
        /// <param name="destination">The destination image.</param>
        /// <param name="configuration">The configuration.</param>
        /// <returns>
        /// The <see cref="bool" />
        /// </returns>
        private bool OptimizedApply(ImageFrame <TPixel> source, ImageFrame <TPixel> destination, Configuration configuration)
        {
            // Wrap the degrees to keep within 0-360 so we can apply optimizations when possible.
            float degrees = WrapDegrees(this.Degrees);

            if (MathF.Abs(degrees) < Constants.Epsilon)
            {
                // The destination will be blank here so copy all the pixel data over
                source.GetPixelSpan().CopyTo(destination.GetPixelSpan());
                return(true);
            }

            if (MathF.Abs(degrees - 90) < Constants.Epsilon)
            {
                this.Rotate90(source, destination, configuration);
                return(true);
            }

            if (MathF.Abs(degrees - 180) < Constants.Epsilon)
            {
                this.Rotate180(source, destination, configuration);
                return(true);
            }

            if (MathF.Abs(degrees - 270) < Constants.Epsilon)
            {
                this.Rotate270(source, destination, configuration);
                return(true);
            }

            return(false);
        }