public static double simpsonRuleM(Expr expr, string varName, double a, double b)
        {
            var f = expr.Compile(varName);

            f = Differentiate.SecondDerivativeFunc(Differentiate.SecondDerivativeFunc(f));

            return(max(f(a), f(b)));
        }
Exemple #2
0
        private Matrix <double> CalculateJacobi()
        {
            var fun      = SetupFunction();
            var jacobian = Matrix <double> .Build.Dense(6, 6);

            for (int i = 0; i < NO_OF_LEGS; i++)
            {
                UpdateVariables(i);
                for (int j = 0; j < NO_OF_LEGS; j++)
                {
                    double valueDerivative = Differentiate.FirstPartialDerivative(fun, variables, j);
                    valueDerivative = serviceConverter.ConvertToFourDecimalPlaces(valueDerivative);
                    jacobian[i, j]  = valueDerivative;
                }
            }
            return(jacobian);
        }
Exemple #3
0
        private void NiutonoMetodas(Func <double, double> funkcija)
        {
            double x0 = 5;
            double abs;
            int    i                = 1;
            double prec             = 0.0001;
            int    kvietimuSkaicius = 0;
            double yy1              = Differentiate.Derivative(funkcija, x0, 1);
            double yy2              = Differentiate.Derivative(funkcija, x0, 2);

            kvietimuSkaicius += 2;
            double x1 = x0 - (yy1 / yy2);

            abs = Math.Abs(x1 - x0);

            Console.WriteLine("\n|| Niutono metodas ||\n");

            chartNewton.Series["x0"].Points.AddXY(i, x0);
            chartNewton.Series["x1"].Points.AddXY(i, x1);

            string[] row = { i.ToString(), x0.ToString(), x1.ToString(), (x0 - x1).ToString("0." + new string('#', 339)) };
            dataGridViewNewton.Rows.Add(row);

            while (!(abs < prec))
            {
                yy1 = Differentiate.Derivative(funkcija, x1, 1);
                yy2 = Differentiate.Derivative(funkcija, x1, 2);
                kvietimuSkaicius += 2;
                i++;
                x0 = x1 - (yy1 / yy2);
                var temp = x1;
                x1 = x0;
                x0 = temp;

                abs = Math.Abs(x1 - x0);
                chartNewton.Series["x0"].Points.AddXY(i, x0);
                chartNewton.Series["x1"].Points.AddXY(i, x1);
                row = new string[] { i.ToString(), x0.ToString(), x1.ToString(), (x0 - x1).ToString("0." + new string('#', 339)) };
                dataGridViewNewton.Rows.Add(row);
            }
            kvietimuSkaicius += 1;
            Console.WriteLine("Prireike {0} iteraciju bei {1} funkcijos kvietimu", i, kvietimuSkaicius);
            Console.WriteLine("Atsakymas yra X = {0} Y = {1}", x1, funkcija(x1));
        }
Exemple #4
0
 public virtual double DerivInvF(double z)
 {
     return(Differentiate.FirstDerivative(InvF, z));
 }
Exemple #5
0
 public virtual double DerivF(double x)
 {
     return(Differentiate.FirstDerivative(F, x));
 }
        public static double fourthDerivative(Expr expr, string varName, double x)
        {
            var f = expr.Compile(varName);

            return(Differentiate.SecondDerivative(Differentiate.SecondDerivativeFunc(f), x));
        }
Exemple #7
0
        private void calculateMemoryAllocations()
        {
            foreach (EssesFileCacheContext fileCache in this.fileCaches.Values)
            {
                List <IInterpolation> utilities = new List <IInterpolation>();
                List <UInt64>         minNecessaryAllocations = new List <UInt64>();
                List <UInt64>         finalAllocations        = new List <UInt64>();

                UInt64 epsilon = 1048576; //Water-filling constant ; XXIS: PICK A GOOD VALUE FOR THIS

                List <uint> flowsInAllocation = new List <uint>();
                foreach (Flow flow in fileCache.flows)
                {
                    EssesFlowCacheContext flowCacheContext = (EssesFlowCacheContext)flow.Context;

                    UInt64 flowBWSLA = flowCacheContext.guaranteedE2EBW;
                    double numerator = (double)(flowBWSLA - this.remoteStorageBW);
                    double deminator = (double)(this.localCacheBW - this.remoteStorageBW);

                    double necessaryHitRate = numerator / deminator;

                    Double[] newYVals = new Double[flowCacheContext.cacheDemandCurvePoints.yVals.Length];

                    for (int j = 0; j < flowCacheContext.cacheDemandCurvePoints.yVals.Length; j++)
                    {
                        newYVals[j] = necessaryHitRate - flowCacheContext.cacheDemandCurvePoints.yVals[j];
                    }

                    Func <double, double> rootFunc = Fit.PolynomialFunc(flowCacheContext.cacheDemandCurvePoints.xVals, newYVals, 10);


                    //double reqCacheSize = MathNet.Numerics.RootFinding.Bisection.FindRoot(rootFunc, 0, (double)fileCache.fileCacheSize);
                    double reqCacheSize; // = MathNet.Numerics.RootFinding.RobustNewtonRaphson.FindRoot(rootFunc, Differentiate.FirstDerivativeFunc(rootFunc), 0, (double)fileCache.fileCacheSize, 1e-3);

                    if (MathNet.Numerics.RootFinding.RobustNewtonRaphson.TryFindRoot(rootFunc, Differentiate.FirstDerivativeFunc(rootFunc), 0, (double)fileCache.fileCacheSize, 1e-3, 100, 20, out reqCacheSize))
                    {
                    }

                    utilities.Add(flowCacheContext.cacheDemandFunc);
                    minNecessaryAllocations.Add((UInt64)reqCacheSize);
                    flowsInAllocation.Add(flow.FlowId);
                }


                UtilityMaximizationAllocation(fileCache.fileCacheSize, utilities, minNecessaryAllocations, epsilon, finalAllocations);

                int i = 0; //counter for flows that were allocated cache this iteration (with flowIDs in flowsInAllocation)
                foreach (Flow flow in fileCache.flows)
                {
                    string responseString         = "";
                    EssesFlowCacheContext context = (EssesFlowCacheContext)flow.Context;

                    if (flowsInAllocation.Contains(flow.FlowId))
                    {
                        if (finalAllocations[i] != context.cacheSizeAllocated)
                        {
                            //Response string example; commands to cache module can be any number of the commands below in the same message (in any order)
                            responseString            += "changeCacheSize=" + finalAllocations[i].ToString() + " ";
                            context.cacheSizeAllocated = finalAllocations[i]; //update our own state of the new flow cache size

                            //if we changed the cache size, reset the counters to compute hit rate (client is doing so too)
                            context.cacheAccessesTotal     = 0;
                            context.cacheAccessesHitsTotal = 0;
                        }
                        i++; //only increment when we see a flow we allocated cache to
                    }
                    else //flow is idle; not included in cache allocation
                    {
                        if (context.cacheSizeAllocated != 0)
                        {
                            responseString            += "changeCacheSize=0";
                            context.cacheSizeAllocated = 0; //update our own state of the new flow cache size

                            //if we changed the cache size, reset the counters to compute hit rate (client is doing so too)
                            context.cacheAccessesTotal     = 0;
                            context.cacheAccessesHitsTotal = 0;
                        }
                    }

                    //ADD WHATEVER OTHER PARAMETERS YOU WANT TO CHANGE THE CLIENT CACHE HERE
                    flow.IoFlowUpdateParams = responseString; //XXXIS: parameters to update flow get put in responseString
                }
            }
        }
        public static double firstDerivative(Expr expr, string varName, double x)
        {
            var f = expr.Compile(varName);

            return(Differentiate.FirstDerivative(f, x));
        }
 protected double Derivative(double inputX, int order)
 {
     return(Differentiate.Derivative(CalculateByPoint, inputX, order));
 }
 protected double SecondDerivative(double inputX)
 {
     return(Differentiate.SecondDerivative(CalculateByPoint, inputX));
 }
 protected double FirstDerivative(double inputX)
 {
     return(Differentiate.FirstDerivative(CalculateByPoint, inputX));
 }
Exemple #12
0
        public const double g = 9.80665; // aceleração da gravidade [m/s^2]

        /// <summary>
        /// Calcula a primeira derivada da função func no ponto x
        /// <param name="func">A função que vai ser derivada. </param>
        /// <param name="x">O ponto em que se deseja calcular a derivada. </param>
        /// <returns> dfunc(x)/dx. </returns>
        /// </summary>
        public double PrimeiraDerivada(Func <double, double> func, double x)
        {
            return(Differentiate.FirstDerivative(func, x));
        }
        /// <summary>
        /// Spawns cubes upon an arc of an ellipse.
        /// </summary>
        /// <param name="n"> The number of cubes. </param>
        /// <param name="center"> The center of the ellipse. </param>
        /// <param name="sectorChordLength"> The length of the arc's chord. </param>
        /// <param name="semiMinorAxisLength"> Half the length of the minor axis. </param>
        /// <param name="sectorAngleDeg"> The angular length of the arc in degrees. </param>
        /// <param name="cubePrefab"> The template for the cubes. </param>
        /// <param name="parent"> The parent of the cubes structure. </param>
        /// <returns> Returns the GameObject containing the cubes, whose parent is 'parent'. </returns>
        /// <remarks> This function is definitely very time-expensive. Use sparingly. </remarks>
        private static GameObject SpawnEllipseCubes(int n, Vector3 center, float sectorChordLength, float semiMinorAxisLength, float sectorAngleDeg, GameObject cubePrefab, Transform parent = null)
        {
            // TODO: Find constraints for every parameter and variable (minimum and maximum values)
            //       Problem: for some combination of input parameters, the FindRoots.OfFunction method fails with an exception:
            //                "ArithmeticException: Function does not accept floating point Not-a-Number values."
            //       Sample parameters: (16,, 12.0f, 6.0f, 90°,,)

            #region Maths

            /*
             * C: center of the ellipse
             * R: sectorChordLength, the length of the chord
             * a: half the length of the major axis of the ellipse
             * b: semiMinorAxisLength, half the length of the minor axis of the ellipse
             * α: sectorAngleDeg, the sector extension in degrees, from (90° - α/2) to (90° + α/2) counterclock-wise
             * n: number of cubes
             *
             *
             * § 1) ELLIPSE'S EQUATIONS
             *
             * ξ(ϑ): ellipse's parametric equations [-180° ≤ ϑ ≤ 180°]
             *     where ϑ is the angle of (ξˣ(ϑ), ξʸ(ϑ)) with the major axis of the ellipse itself
             *                       ___________________________
             *   ξˣ(ϑ) = a b cos(ϑ) √(a² sin²(ϑ) + b² cos²(ϑ))⁻¹
             *                       ___________________________
             *   ξʸ(ϑ) = a b sin(ϑ) √(a² sin²(ϑ) + b² cos²(ϑ))⁻¹
             *
             * A = ξ(90° + α/2)
             * B = ξ(90° - α/2)
             *
             *     __                   _______________________________
             * R = AB = 2 a b sin(α/2) √(a² cos²(α/2) + b² sin²(α/2))⁻¹
             *      _________________________________________                   _______________________
             * a = √(b² R² tan²(α/2)) / (4 b² tan²(α/2) - R²) = (b R tan(α/2)) √(4 b² tan²(α/2) - R²)⁻¹
             *
             *
             * § 2) CUBES PLACEMENT
             *      A _____________________
             * L = ∫(√D[ξˣ(ϑ)]² + D[ξʸ(ϑ)]²)dϑ: length of arc AB
             *    B
             * l = L/n: distance between each cube's center on the arc
             *
             * θᵢ: angle of the iᵗʰ arc segment; arc length to the iᵗʰ arc segment = i l
             * θᵢ = FindRoot[∫(D[ξˣ(ϑ)]² + D[ξʸ(ϑ)]²)dϑ = i l]   😭
             *
             * Pᵢ = ξ(θᵢ): position of the iᵗʰ cube
             *
             *
             * § 3) CUBES' SIDE LENGTH
             * Let Pᵢ and Pⱼ be the positions of two consecutive cubes (j = i + 1) with angles θᵢ and θⱼ.
             * Let Pₖ be a third point placed at the same arc-distance from both Pᵢ and Pⱼ; the angle of Pₖ is θₖ.
             *
             * rₖ: line from C to Pₖ
             * rᵢ: line from C to Pᵢ
             * rⱼ: line from C to Pⱼ
             *
             * M: parametric point on rₖ
             * dᵢ: segment MPᵢ
             * dⱼ: segment MPⱼ
             *
             *
             * M = (mˣ, mʸ) = (mˣ, mˣ tan(θₖ))
             *       ____________________________________
             * dᵢ = √(x(Pᵢ) - mˣ)² + (y(Pᵢ) - mˣ tan(θₖ))²
             *       ____________________________________
             * dⱼ = √(x(Pⱼ) - mˣ)² + (y(Pⱼ) - mˣ tan(θₖ))²
             *
             * ASSERTION
             * dᵢ = dⱼ = d: dᵢ and dⱼ are the semi-diagonals of the two squares
             *
             * (x(Pᵢ) - mˣ)² + (y(Pᵢ) - mˣ tan(θₖ))² = (x(Pⱼ) - mˣ)² + (y(Pⱼ) - mˣ tan(θₖ))²
             * x(Pᵢ)² + (mˣ)² - 2 x(Pᵢ) mˣ + y(Pᵢ)² + (mˣ tan(θₖ))² - 2 y(Pᵢ) mˣ tan(θₖ)  =  x(Pⱼ)² + (mˣ)² - 2 x(Pⱼ) mˣ + y(Pⱼ)² + (mˣ tan(θₖ))² - 2 y(Pⱼ) mˣ tan(θₖ)
             * x(Pᵢ)² - 2 x(Pᵢ) mˣ + y(Pᵢ)² - 2 y(Pᵢ) mˣ tan(θₖ)  =  x(Pⱼ)² - 2 x(Pⱼ) mˣ + y(Pⱼ)² - 2 y(Pⱼ) mˣ tan(θₖ)
             * 2 x(Pⱼ) mˣ + 2 y(Pⱼ) mˣ tan(θₖ) - 2 x(Pᵢ) mˣ - 2 y(Pᵢ) mˣ tan(θₖ)  =  x(Pⱼ)² + y(Pⱼ)² - x(Pᵢ)² - y(Pᵢ)²
             * 2 mˣ (x(Pⱼ) + y(Pⱼ) tan(θₖ) - x(Pᵢ) - y(Pᵢ) tan(θₖ))  =  x(Pⱼ)² + y(Pⱼ)² - x(Pᵢ)² - y(Pᵢ)²
             *
             *              x(Pⱼ)² + y(Pⱼ)² - x(Pᵢ)² - y(Pᵢ)²
             * mˣ = ——————————————————————————————————————————————————
             *       2 (x(Pⱼ) + y(Pⱼ) tan(θₖ) - x(Pᵢ) - y(Pᵢ) tan(θₖ))
             *
             * cube's side length = 2 (d/√2)
             *
             */

            #endregion Maths

            double R = sectorChordLength;
            double b = semiMinorAxisLength;

            #region § 1) ELLIPSE'S EQUATION

            double alphaRad      = Trig.DegreeToRadian(sectorAngleDeg);
            double bTanHalfAlpha = b * Trig.Tan(alphaRad / 2.0);
            double a             = (R * bTanHalfAlpha) / Math.Sqrt(4 * bTanHalfAlpha * bTanHalfAlpha - R * R);

            Func <double, double> EllipseX = t =>
            {
                double sin  = Trig.Sin(t);
                double cos  = Trig.Cos(t);
                double aSin = a * sin;
                double bCos = b * cos;
                return((a * bCos) / Math.Sqrt(aSin * aSin + bCos * bCos));
            };
            Func <double, double> EllipseY = t =>
            {
                double sin  = Trig.Sin(t);
                double cos  = Trig.Cos(t);
                double aSin = a * sin;
                double bCos = b * cos;
                return((b * aSin) / Math.Sqrt(aSin * aSin + bCos * bCos));
            };

            #endregion § 1) ELLIPSE'S EQUATION

            #region § 2) CUBES PLACEMENT

            Func <double, double> DEllipseX = Differentiate.FirstDerivativeFunc(EllipseX);
            Func <double, double> DEllipseY = Differentiate.FirstDerivativeFunc(EllipseY);

            Func <double, double> SqrtOfSumOfSquaredDerivatives = t =>
            {
                double x = DEllipseX(t);
                double y = DEllipseY(t);
                return(Math.Sqrt(x * x + y * y));
            };

            Func <double, double, double> AngleToArcLength = (fromRad, toRad) => Integrate.OnClosedInterval(SqrtOfSumOfSquaredDerivatives, fromRad, toRad);
            Func <double, double>         ArcLengthToAngle = arcLength => FindRoots.OfFunction(toRad => AngleToArcLength((Math.PI - alphaRad) / 2, toRad) - arcLength, 0, Math.PI);

            double L = AngleToArcLength((Math.PI - alphaRad) / 2, (Math.PI + alphaRad) / 2);
            double l = L / (n - 1);

            Func <int, object[]> CalculateCubePositionAndAngle = i =>
            {
                double  angle    = ArcLengthToAngle(i * l);
                Vector2 position = new Vector2((float)EllipseX(angle), (float)EllipseY(angle));
                return(new object[] { position, angle });
            };

            #endregion § 2) CUBES PLACEMENT

            #region § 3) CUBES' SIDE LENGTH

            Vector2[] positions    = new Vector2[n];
            double[]  angles       = new double[n];
            double[]  middleAngles = new double[n - 1];
            for (int i = 0; i < n; ++i)
            {
                object[] res = CalculateCubePositionAndAngle(i);
                positions[i] = (Vector2)res[0];
                angles[i]    = (double)res[1];

                if (i > 0)
                {
                    middleAngles[i - 1] = ArcLengthToAngle((2 * i - 1) * l / 2.0);
                }
            }

            double[]           sideLengths = new double[n - 1];
            Func <int, double> SideLength  = j =>
            {
                double xj   = positions[j].x;
                double yj   = positions[j].y;
                double xi   = positions[j - 1].x;
                double yi   = positions[j - 1].y;
                double tanK = Trig.Tan(middleAngles[j - 1]);
                double mx   = (xj * xj + yj * yj - (xi * xi + yi * yi)) / (2.0 * (xj + yj * tanK - (xi + yi * tanK)));
                return(Math.Sqrt((xi - mx) * (xi - mx) + (yi - mx * tanK) * (yi - mx * tanK)) * (2.0 / Math.Sqrt(2.0)));
            };
            for (int i = 1; i < n; ++i)
            {
                sideLengths[i - 1] = SideLength(i);
            }

            float squareSide = (float)sideLengths.Min();

            #endregion § 3) CUBES' SIDE LENGTH

            // Save parent's current local rotation and scale; it will be re-set later
            Quaternion parentRotation = parent?.localRotation ?? Quaternion.identity;
            Vector3    parentScale    = parent?.localScale ?? Vector3.one;
            if (parent != null)
            {
                parent.localRotation = Quaternion.identity;
                parent.localScale    = Vector3.one;
            }

            GameObject cubesContainer = parent?.gameObject ?? new GameObject();
            cubesContainer.name = $"Ellipse_{n}Cubes";
            cubesContainer.transform.localPosition = center;

            // Create the cubes
            for (int i = 0; i < n; ++i)
            {
                GameObject cube = Instantiate(cubePrefab);
                cube.name = $"Cube{i}";
                cube.SetActive(true); // Awake it now, to let it store the prefab's original scale
                cube.transform.localScale    = new Vector3(squareSide, squareSide, squareSide);
                cube.transform.position      = cubesContainer.transform.position + new Vector3(positions[i].x, 0.0f, positions[i].y);
                cube.transform.localRotation = Quaternion.Euler(0.0f, (float)(90.0 - Trig.RadianToDegree(angles[i])), 0.0f);
                cube.transform.parent        = cubesContainer.transform;
            }
            cubesContainer.transform.localRotation = Quaternion.identity;

            // Re-set parent's original local rotation
            if (parent != null)
            {
                parent.localRotation = parentRotation;
                parent.localScale    = parentScale;
            }

            return(cubesContainer);
        }