Ejemplo n.º 1
0
 public Color ConvertLinearToGamma()
 {
     this.R = (int)SMath.Sqrt(this.R);
     this.G = (int)SMath.Sqrt(this.G);
     this.B = (int)SMath.Sqrt(this.B);
     return(this);
 }
Ejemplo n.º 2
0
        // For performance improvements Color and Spatial functions are recalculated prior to filter execution and put into 2 dimensional arrays
        private void InitSpatialFunc( )
        {
            if ((spatialFunc == null) || (spatialFunc.Length != kernelSize * kernelSize) ||
                (spatialPropertiesChanged))
            {
                if ((spatialFunc == null) || (spatialFunc.Length != kernelSize * kernelSize))
                {
                    spatialFunc = new double[kernelSize, kernelSize];
                }

                int kernelRadius = kernelSize / 2;

                for (int i = 0; i < kernelSize; i++)
                {
                    int ti  = i - kernelRadius;
                    int ti2 = ti * ti;

                    for (int k = 0; k < kernelSize; k++)
                    {
                        int tk  = k - kernelRadius;
                        int tk2 = tk * tk;

                        spatialFunc[i, k] = M.Exp(-0.5 * M.Pow(M.Sqrt((ti2 + tk2) / spatialFactor), spatialPower));
                    }
                }

                spatialPropertiesChanged = false;
            }
        }
Ejemplo n.º 3
0
 public Color CopyLinearToGamma(Color Color)
 {
     this.R = (int)SMath.Sqrt(Color.R);
     this.G = (int)SMath.Sqrt(Color.G);
     this.B = (int)SMath.Sqrt(Color.B);
     return(this);
 }
Ejemplo n.º 4
0
        // For performance improvements Color and Spatial functions are recalculated prior to filter execution and put into 2 dimensional arrays
        private void InitSpatialFunc( )
        {
            if ((this.spatialFunc == null) || (this.spatialFunc.Length != this.kernelSize * this.kernelSize) ||
                (this.spatialPropertiesChanged))
            {
                if ((this.spatialFunc == null) || (this.spatialFunc.Length != this.kernelSize * this.kernelSize))
                {
                    this.spatialFunc = new double[this.kernelSize, this.kernelSize];
                }

                var kernelRadius = this.kernelSize / 2;

                for (var i = 0; i < this.kernelSize; i++)
                {
                    var ti  = i - kernelRadius;
                    var ti2 = ti * ti;

                    for (var k = 0; k < this.kernelSize; k++)
                    {
                        var tk  = k - kernelRadius;
                        var tk2 = tk * tk;

                        this.spatialFunc[i, k] = M.Exp(-0.5 * M.Pow(M.Sqrt((ti2 + tk2) / this.spatialFactor), this.spatialPower));
                    }
                }

                this.spatialPropertiesChanged = false;
            }
        }
Ejemplo n.º 5
0
        public static bool Intersect(Sphere sphere, Ray ray, out Num distance)
        {
            distance = 0;

            var l = sphere.Center - ray.Org;
            var a = Vec3.Dot(l, ray.Dir);

            if (a < 0)                          // opposite direction
            {
                return(false);
            }

            var b2 = Vec3.Dot(l, l) - (a * a);
            var r2 = sphere.Radius * sphere.Radius;

            if (b2 > r2)                        // perpendicular > r
            {
                return(false);
            }

            Num c    = MATH.Sqrt(r2 - b2);
            Num near = a - c;
            Num far  = a + c;

            distance = (near < 0) ? far : near;
            // near < 0 means ray starts inside
            return(true);
        }
Ejemplo n.º 6
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);
        }
Ejemplo n.º 7
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);
        }
Ejemplo n.º 8
0
        public bool WasHit(Ray p_ray, double p_tMin, double p_tMax, ref HitRecord p_hitRecord)
        {
            // If the quadratic is confusing, remember that several 2s are pre-canceled out. - Comment by Matt Heimlich on 06/23/2019 @ 12:15:02
            var oc           = p_ray.Origin - GetCenter(p_ray.Time);
            var a            = Vec3.GetDotProduct(p_ray.Direction, p_ray.Direction);
            var b            = Vec3.GetDotProduct(oc, p_ray.Direction);
            var c            = Vec3.GetDotProduct(oc, oc) - Radius * Radius;
            var discriminant = b * b - a * c;

            if (discriminant > 0)
            {
                var sqrtCache = Math.Sqrt(b * b - a * c);
                var temp      = (-b - sqrtCache) / a;
                if (temp < p_tMax && temp > p_tMin)
                {
                    p_hitRecord.T        = temp;
                    p_hitRecord.Point    = p_ray.PointAt(p_hitRecord.T);
                    p_hitRecord.Normal   = (p_hitRecord.Point - GetCenter(p_ray.Time)) / Radius;
                    p_hitRecord.Material = Material;
                    return(true);
                }
                temp = (-b + sqrtCache) / a;
                if (temp < p_tMax && temp > p_tMin)
                {
                    p_hitRecord.T        = temp;
                    p_hitRecord.Point    = p_ray.PointAt(p_hitRecord.T);
                    p_hitRecord.Normal   = (p_hitRecord.Point - GetCenter(p_ray.Time)) / Radius;
                    p_hitRecord.Material = Material;
                    return(true);
                }
            }

            return(false);
        }
        List <PointF> GenerateRandNormal(int n)
        {
            if (n % 2 == 1)
            {
                n++;
            }

            List <PointF> points = new List <PointF>(n);

            for (int i = 0; i < n / 2; i++)
            {
                do
                {
                    double u = 2 * rnd.NextDouble() - 1;
                    double v = 2 * rnd.NextDouble() - 1;

                    double s = u * u + v * v;

                    if (s < 1)
                    {
                        s = Math.Sqrt(-2 * Math.Log(s) / s);
                        points.Add(new PointF(i, (float)(u * s)));
                        points.Add(new PointF(i + 1, (float)(v * s)));
                        break;
                    }
                } while (true);
            }

            return(points);
        }
Ejemplo n.º 10
0
        public override string ToString()
        {
            var groupInfo   = $"{this.Center} Range={Math.Sqrt(this.Range2)} Weight={this.Weight} WreckCount={this.Wrecks.Count}";
            var bestPosInfo = $"BestPos={this.BestPos} BestWeight={this.BestPosWeight} IsInter={this.IsBestPosInter}";

            return($"WreckGroup {groupInfo} || {bestPosInfo}");
        }
Ejemplo n.º 11
0
 /// <summary>
 /// The total straight length between the offset points.
 /// </summary>
 /// <returns>System.Double.</returns>
 public double Length()
 {
     return(NMath.Sqrt(I.Radius.Squared() + J.Radius.Squared() - 2 * I.Radius * J.Radius * (
                           NMath.Sin(I.Inclination.Radians) * NMath.Sin(J.Inclination.Radians) * NMath.Cos(I.Azimuth.Radians - J.Azimuth.Radians) +
                           NMath.Cos(I.Inclination.Radians) * NMath.Cos(J.Inclination.Radians)
                           )));
 }
Ejemplo n.º 12
0
        public Task <QuotationResult> CalculatePremiums(QuotationInput quoteparams)
        {
            try
            {
                return(Task.Run(() =>
                {
                    double d1 = 0.0;
                    double d2 = 0.0;
                    QuotationResult quotes = new QuotationResult();
                    double S = double.Parse(quoteparams.StockPrice.Replace(".", ","));
                    double K = double.Parse(quoteparams.StrikePrice.Replace(".", ","));
                    double T = double.Parse(quoteparams.TimeToMaturity.Replace(".", ","));
                    double r = double.Parse(quoteparams.InterestRate.Replace(".", ","));
                    double v = double.Parse(quoteparams.Volatility.Replace(".", ","));

                    d1 = Math.Round((Math.Log(S / K) + (r + v * v / 2.0) * T) / v / Math.Sqrt(T), 4);
                    d2 = Math.Round(d1 - v * Math.Sqrt(T), 4);

                    quotes.D1 = d1;
                    quotes.D2 = d2;

                    quotes.CallPremium = Math.Round(S * CumulativeNormDistFunction(d1) - K * Math.Exp(-r * T) * CumulativeNormDistFunction(d2), 4);
                    quotes.PutPremium = Math.Round(K * Math.Exp(-r * T) * CumulativeNormDistFunction(-d2) - S * CumulativeNormDistFunction(-d1), 4);

                    return quotes;
                }));
            }
            catch (Exception ex)
            {
                throw;
            }
        }
Ejemplo n.º 13
0
 static double CumulativeNormDistFunction(double x)
 {
     try
     {
         double b0 = 0.2316419;
         double b1 = 0.319381530;
         double b2 = -0.356563782;
         double b3 = 1.781477937;
         double b4 = -1.821255978;
         double b5 = 1.330274429;
         double pi = Math.PI;
         double phi = Math.Exp(-x * x / 2.0) / Math.Sqrt(2.0 * pi);
         double t, c;
         double CDF = 0.5;
         if (x > 0.0)
         {
             t   = 1.0 / (1.0 + b0 * x);
             CDF = 1.0 - phi * (b1 * t + b2 * Math.Pow(t, 2) + b3 * Math.Pow(t, 3) + b4 * Math.Pow(t, 4) + b5 * Math.Pow(t, 5));
         }
         else if (x < 0.0)
         {
             x   = -x;
             t   = 1.0 / (1.0 + b0 * x);
             c   = 1.0 - phi * (b1 * t + b2 * Math.Pow(t, 2) + b3 * Math.Pow(t, 3) + b4 * Math.Pow(t, 4) + b5 * Math.Pow(t, 5));
             CDF = 1.0 - c;
         }
         return(CDF);
     }
     catch (Exception ex)
     {
         throw;
     }
 }
Ejemplo n.º 14
0
        public static Vector2D GetProjectedPointOnLine(Vector2D v1, Vector2D v2, Vector2D p, bool disableBBcheck = false)
        {
            Func <Vector2D, Vector2D, double> dotProduct = (a, b) =>
            {
                return(a.X * b.X + a.Y * b.Y);
            };

            var    e1            = new Vector2D(v2.X - v1.X, v2.Y - v1.Y);
            var    e2            = new Vector2D(p.X - v1.X, p.Y - v1.Y);
            double valDp         = dotProduct(e1, e2);
            double lenLineE1     = SysMath.Sqrt(e1.X * e1.X + e1.Y * e1.Y);
            double lenLineE2     = SysMath.Sqrt(e2.X * e2.X + e2.Y * e2.Y);
            double cos           = valDp / (lenLineE1 * lenLineE2);
            double projLenOfLine = cos * lenLineE2;
            var    qp            = new Vector2D((v1.X + (projLenOfLine * e1.X) / lenLineE1), (v1.Y + (projLenOfLine * e1.Y) / lenLineE1));

            if (!disableBBcheck)
            {
                if (!IsPointInsideBoundingBox(v1, v2, qp))
                {
                    return(null);
                }
            }

            return(qp);
        }
Ejemplo n.º 15
0
        public static Plane CreateFromVertices(Vector3 point1, Vector3 point2, Vector3 point3)
        {
            Plane result;

            float ax = point2.X - point1.X;
            float ay = point2.Y - point1.Y;
            float az = point2.Z - point1.Z;

            float bx = point3.X - point1.X;
            float by = point3.Y - point1.Y;
            float bz = point3.Z - point1.Z;

            // N=Cross(a,b)
            float nx = ay * bz - az * by;
            float ny = az * bx - ax * bz;
            float nz = ax * by - ay * bx;

            // Normalize(N)
            float ls      = nx * nx + ny * ny + nz * nz;
            float invNorm = 1.0f / (float)SM.Sqrt((double)ls);

            result.Normal.X = nx * invNorm;
            result.Normal.Y = ny * invNorm;
            result.Normal.Z = nz * invNorm;

            // D = - Dot(N, point1)
            result.D = -(result.Normal.X * point1.X + result.Normal.Y * point1.Y + result.Normal.Z * point1.Z);

            return(result);
        }
Ejemplo n.º 16
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);
        }
Ejemplo n.º 17
0
        /// <summary>光線r = p + td, |vD| = 1が球sに対して交差しているかどうか。</summary>
        /// <param name="rvP">基点</param>
        /// <param name="vD">方向ベクトル</param>
        /// <param name="rS">対象とする球体</param>
        /// <param name="t">0≦t≦Tmax</param>
        /// <param name="hit">交差した位置</param>
        /// <return>交差している場合、交差している*tの値および交差点*hitを返す</return>
        public static bool IntersectRaySphere(MCVector3 rvP, MCVector3 vD, Sphere rS, out float t, out MCVector3 hit)
        {
            hit = new MCVector3();
            t   = 0;
            MCVector3 vM = rvP - rS.c;
            float     fB = vM.Dot(vD);
            float     fC = vM.Dot(vM) - rS.r * rS.r;

            // rの原点が*rSの外側にあり(c > 0)、rが*rSから離れていく方向を指している場合(fB > 0)に終了
            if (fC > 0.0f && fB > 0.0f)
            {
                return(false);
            }
            float fDiscr = fB * fB - fC;

            // 負の判別式は光線が球を外れていることに一致
            if (fDiscr < 0.0f)
            {
                return(false);
            }
            // これで光線は球と交差していることが分かり、交差する最小の値*tを計算
            t = -fB - (float)Mt.Sqrt(fDiscr);
            // *tが負である場合、光線は球の内側から開始しているので*tをゼロにクランプ
            if (t < 0.0f)
            {
                t = 0.0f;
            }
            hit = rvP + t * vD;
            return(true);
        }
Ejemplo n.º 18
0
        /// <summary>
        /// 将stec转换为vtec
        /// </summary>
        /// <param name="stec"></param>
        /// <param name="ele">高度角(弧度)</param>
        /// <param name="earthRadius">地球半径(默认6371000)</param>
        /// <param name="ionoHeight">电离层单层模型高度(默认450000)</param>
        /// <returns></returns>
        public static double STEC2VTEC(double stec, double ele, double earthRadius = 6371100, double ionoHeight = 450000)
        {
            double sinz  = Math.Sin(PI / 2d - ele);
            double sinzz = earthRadius / (earthRadius + ionoHeight) * sinz;
            double coszz = Math.Sqrt(1d - sinzz * sinzz);

            return(stec * coszz);
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Returns the x solution to the equation ax^2 + bx + c = 0.
        /// </summary>
        /// <param name="a">Multiplier to x^2.</param>
        /// <param name="b">Multiplier to x.</param>
        /// <param name="c">Constant.</param>
        /// <returns></returns>
        public static double[] QuadraticFormula(double a, double b, double c)
        {
            double denominator = 2 * a;
            double operand1    = -b / denominator;
            double operand2    = NMath.Sqrt(b.Squared() - 4 * a * c) / denominator;

            return(operand1.PlusMinus(operand2));
        }
Ejemplo n.º 20
0
        public static double Distance(Vector3D value1, Vector3D value2)
        {
            double num1 = value1.X - value2.X;
            double num2 = value1.Y - value2.Y;
            double num3 = value1.Z - value2.Z;

            return(SystemMath.Sqrt(num1 * num1 + num2 * num2 + num3 * num3));
        }
Ejemplo n.º 21
0
        public static double Distance(Vector2D x, Vector2D y)
        {
            if (x == null || y == null)
            {
                return(double.MaxValue);
            }

            return(SysMath.Sqrt(SysMath.Pow(y.X - x.X, 2) + SysMath.Pow(y.Y - x.Y, 2)));
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Returns the distance between two vectors.
        /// </summary>
        public static float Distance(Vector3 a, Vector3 b)
        {
            Vector3 diff = new Vector3(
                a.x - b.x,
                a.y - b.y,
                a.z - b.z);

            return((float)Maths.Sqrt(Maths.Pow(diff.x, 2f) + Maths.Pow(diff.y, 2f) + Maths.Pow(diff.z, 2f)));
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Changes the coefficients of the normal vector of the plane to make it of unit length.
        /// </summary>
        /// <param name="plane">The source plane.</param>
        /// <param name="result">When the method completes, contains the normalized plane.</param>
        public static void Normalize(ref Plane plane, out Plane result)
        {
            float magnitude = 1.0f / (float)(SMath.Sqrt((plane.Normal.X * plane.Normal.X) + (plane.Normal.Y * plane.Normal.Y) + (plane.Normal.Z * plane.Normal.Z)));

            result.Normal.X = plane.Normal.X * magnitude;
            result.Normal.Y = plane.Normal.Y * magnitude;
            result.Normal.Z = plane.Normal.Z * magnitude;
            result.D        = plane.D * magnitude;
        }
Ejemplo n.º 24
0
        /// <summary>
        /// Changes the coefficients of the normal vector of the plane to make it of unit length.
        /// </summary>
        public void Normalize()
        {
            float magnitude = 1.0f / (float)(SMath.Sqrt((Normal.X * Normal.X) + (Normal.Y * Normal.Y) + (Normal.Z * Normal.Z)));

            Normal.X *= magnitude;
            Normal.Y *= magnitude;
            Normal.Z *= magnitude;
            D        *= magnitude;
        }
Ejemplo n.º 25
0
        public static float Distance(Vector2 value1, Vector2 value2)
        {
            float dx = value1.X - value2.X;
            float dy = value1.Y - value2.Y;

            float ls = dx * dx + dy * dy;

            return((float)SM.Sqrt((double)ls));
        }
Ejemplo n.º 26
0
        public void Jump(float height)
        {
            var velocity = Body.GetLinearVelocity();

            var vYForHeight = (float)Math.Sqrt(2f * 9.8f * height);

            velocity.Y = -vYForHeight;
            Body.SetLinearVelocity(velocity);
        }
    public double NextGaussian()
    {
        const double mean = 0, stdDev = 1;

        double u1            = 1.0 - rand.NextDouble();
        double u2            = 1.0 - rand.NextDouble();
        double randStdNormal = Math.Sqrt(-2.0 * Math.Log(u1)) * Math.Sin(2.0 * Math.PI * u2);

        return(mean + stdDev * randStdNormal);
    }
Ejemplo n.º 28
0
        /// <summary>
        ///     Standard Deviation of Y (requires at least 2 samples)
        /// </summary>
        /// <returns>Standard Deviation of Y</returns>
        public double Qy()
        {
            if (!(N > 1))
            {
                throw new InvalidOperationException(
                          "There must be more than one sample to find the Standard Deviation.");
            }

            return(Math.Sqrt(Sy2 - Math.Pow(Sy, 2) / N) / (N - 1));
        }
Ejemplo n.º 29
0
 /// <summary>
 /// The y-coordinates of a line intersecting a circle centered at 0,0.
 /// </summary>
 /// <param name="radius"></param>
 /// <param name="lineLength"></param>
 /// <param name="incidence"></param>
 /// <param name="determinant"></param>
 /// <param name="delta"></param>
 /// <returns></returns>
 public static double[] CircleLineIntersectY(
     double radius,
     double lineLength,
     double incidence,
     double determinant,
     Offset delta)
 {
     return((-determinant * delta.X() / lineLength.Squared()).PlusMinus(
                NMath.Abs(delta.Y()) * NMath.Sqrt(incidence) / lineLength.Squared()));
 }
Ejemplo n.º 30
0
        /// <summary>
        /// Performs the square root of the sum of the squares of the provided values.
        /// </summary>
        /// <param name="values"></param>
        /// <returns></returns>
        public static double SRSS(params double[] values)
        {
            double sumOfSquares = 0;

            foreach (double value in values)
            {
                sumOfSquares += value.Squared();
            }

            return(NMath.Sqrt(sumOfSquares));
        }