Exemplo n.º 1
0
        public euler3()
        {
            /*
             *      The prime factors of 13195 are 5, 7, 13 and 29.
             *      What is the largest prime factor of the number 600851475143 ?
             */
            const long numm = 600851475143;

            long largestFact = 0;



            for (long i = 2; i *i < numm; i++)
            {
                if (numm % i == 0)
                {
                    if (MathMethods.isPrime(i) && i > largestFact)
                    {
                        largestFact = i;
                    }
                }
            }

            Console.WriteLine(largestFact);
        }
Exemplo n.º 2
0
        static void Main(string[] args)
        {
            MathMethods Math = new MathMethods();

            Console.WriteLine(Math.Fatcorial(5));
            Console.WriteLine(Math.Exponential(5, 2));
        }
Exemplo n.º 3
0
        public euler4()
        {
            /*
             * A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
             * Find the largest palindrome made from the product of two 3-digit numbers.
             */

            var    digits = MathMethods.nrOfDigits(3);
            int    smallDigits = 100;
            int    x, y;
            string product = "0", res = "0";

            for (x = smallDigits; x <= digits; x++)
            {
                for (y = smallDigits; y <= digits; y++)
                {
                    product = Convert.ToString(x * y);

                    if (MathMethods.isPalinDrome(product))
                    {
                        if (x * y > Convert.ToInt32(res))
                        {
                            res = product;
                        }
                    }
                }
            }

            Console.WriteLine(res);
        }
Exemplo n.º 4
0
        public void FloorTest(decimal number)
        {
            MathMethods mathMethods  = new MathMethods();
            decimal     result       = mathMethods.Floor(number);
            decimal     wantedResult = Math.Floor(number);

            Assert.That(result.Equals(wantedResult));
        }
Exemplo n.º 5
0
        /// <summary>
        ///     Constructs a DirectX9 surface for this image from a PixelMap.
        /// </summary>
        /// <param name="pixelMap">PixelMap to construct surface from.</param>
        void ConstructFromPixelMap(PixelMap pixelMap)
        {
            _pixelMap = pixelMap;

            // Work out size of texture to create so that we have a nice square texture.
            if (_dx9Driver.DX9Device.DeviceCaps.TextureCaps.SupportsSquareOnly == true || _dx9Driver.DX9Device.DeviceCaps.TextureCaps.SupportsPower2 == true)
            {
                if (pixelMap.Width > pixelMap.Height)
                {
                    _textureWidth  = MathMethods.Pow(pixelMap.Width, 2);
                    _textureHeight = _textureWidth;
                }
                else
                {
                    _textureHeight = MathMethods.Pow(pixelMap.Height, 2);
                    _textureWidth  = _textureHeight;
                }
            }
            else
            {
                _textureWidth  = pixelMap.Width;
                _textureHeight = pixelMap.Height;
            }

            // Create texture.
            _texture = new Texture(_dx9Driver.DX9Device, _textureWidth, _textureHeight, 1, Usage.None, Format.A8R8G8B8, Pool.Managed);

            // Copy the pixelMap and resize it.
            PixelMap copy = new PixelMap(_textureWidth, _textureHeight);

            copy.Fill(0x00000000);
            copy.Paste(pixelMap, 0, 0);

            // Add memory pressure so the GC collects faster.
            _memoryPressure = copy.Data.Length;
            GC.AddMemoryPressure(_memoryPressure);

            // Create a buffer and then write the image data into it.
            int            pitch;
            GraphicsStream stream = _texture.LockRectangle(0, 0, out pitch);

            stream.Write(copy.Data);
            _texture.UnlockRectangle(0);

            // Sets up the vertex-buffer so all our data is correct
            _vertexArray[0].X = 0;
            _vertexArray[0].Y = 0;
            _vertexArray[1].X = _textureWidth;
            _vertexArray[1].Y = 0;
            _vertexArray[2].X = _textureWidth;
            _vertexArray[2].Y = _textureHeight;
            _vertexArray[3].X = 0;
            _vertexArray[3].Y = _textureHeight;

            // Hook into the dx9 disposal event so we can clean up.
            _dx9Driver.DX9Device.Disposing += new EventHandler(DX9Device_Disposing);
        }
Exemplo n.º 6
0
        public void TestMatrixAddition()
        {
            var matrixA = new double[] { 1, 7, 3 };
            var matrixB = new double[] { 7, 18, 9 };

            var newMatrix = MathMethods.MatrixAdd(matrixA, matrixB);

            Assert.AreEqual(25, newMatrix[1]);
        }
Exemplo n.º 7
0
        /// <summary>
        ///		Translates this entity relative to its currently rotation and position.
        /// </summary>
        /// <param name="x">Amount on the x-axis to translate this entity by.</param>
        /// <param name="y">Amount on the y-axis to translate this entity by.</param>
        /// <param name="z">Amount on the z-axis to translate this entity by.</param>
        public void Translate(float x, float y, float z)
        {
            float mx = ((float)Math.Cos(MathMethods.DegreesToRadians(_transformation.AngleX)) * x);
            float my = -((float)Math.Sin(MathMethods.DegreesToRadians(_transformation.AngleY)) * y);

            _transformation.X += my;
            _transformation.Y += mx;
            _transformation.Z += z;
            Transformation     = _transformation;
        }
Exemplo n.º 8
0
        public void TestMatrixMultiplication()
        {
            var matrixA = new double[, ] {
                { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 }
            };
            var matrixB = new double[] { 7, 8, 9 };

            var newMatrix = MathMethods.MatrixMultiply(matrixA, matrixB);

            Assert.AreEqual(122, newMatrix[1]);
        }
Exemplo n.º 9
0
        static void Main(string[] args)
        {
            // all features: FULXY-NADQW-ZAMPX-PQHUT
            // just abs method: KDDSE-QWAOT-LGFUL-JLZTM

            var math = new MathMethods("FULXY-NADQW-ZAMPX-PQHUT");

            Console.WriteLine(math.Abs(5));
            Console.WriteLine(math.Fibonacci(5));

            Console.ReadLine();

            return;
        }
Exemplo n.º 10
0
        private void Result_Click(object sender, RoutedEventArgs e)
        {
            var value = Double.Parse(InputTextBox.Text);

            if (lastValue == null)
            {
                lastValue = value;
            }
            else
            {
                lastValue = MathMethods.Calculate((double)lastValue, value, sign);
            }
            InputTextBox.Text  = lastValue.ToString();
            OutputTextBox.Text = "";
            lastValue          = null;
        }
Exemplo n.º 11
0
        private void result_Click(object sender, EventArgs e)
        {
            var value = Double.Parse(input.Text);

            if (lastValue == null)
            {
                lastValue = value;
            }
            else
            {
                lastValue = MathMethods.Calculate((double)lastValue, value, sign);
            }
            input.Text          = lastValue.ToString();
            textBox_result.Text = "";
            lastValue           = null;
        }
Exemplo n.º 12
0
        /*
         *      The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
         *      Find the sum of all the primes below two million.
         */

        public euler10()
        {
            int boundary = 2000000;

            long sum = 0;

            for (int i = 0; i < boundary; i++)
            {
                if (MathMethods.isPrime(i))
                {
                    sum += i;
                }
            }

            Console.WriteLine(sum);
        }
Exemplo n.º 13
0
        private void Operatoin_Click(object sender, RoutedEventArgs e)
        {
            var value = Double.Parse(InputTextBox.Text);

            if (lastValue == null)
            {
                lastValue = value;
            }
            else
            {
                lastValue = MathMethods.Calculate((double)lastValue, value, sign);
            }
            OutputTextBox.Text = lastValue + (string)((Button)e.OriginalSource).Content;
            sign = (string)(((Button)e.OriginalSource).Content);
            InputTextBox.Text = "";
        }
Exemplo n.º 14
0
        private void mult_Click(object sender, EventArgs e)
        {
            var value = Double.Parse(input.Text);

            if (lastValue == null)
            {
                lastValue = value;
            }
            else
            {
                lastValue = MathMethods.Calculate((double)lastValue, value, sign);
            }
            textBox_result.Text = lastValue + " x";
            sign       = 3;
            input.Text = "";
        }
Exemplo n.º 15
0
        private void init()
        {
            millerRabbin = new MillerRabin();
            random       = new Random();

            p = GetSimpleNum(length);
            q = GetSimpleNum(length);

            eyler = (p - 1) * (q - 1);
            N     = p * q;

            montRed = new MontgomeryReducer(N);
            expSqr  = new ExponentiationSquaring();

            //byte[] arr = N.ToByteArray();
            e = GetOpenExponent(2 * length / 3);
            d = MathMethods.GCD(e, eyler);
        }
Exemplo n.º 16
0
        /*
         *      2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
         *      What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
         */
        public euler5()
        {
            String smallestDivisible = "";

            int counter = 1;

            while (smallestDivisible.Equals(""))
            {
                if (MathMethods.isDivisibleByRange(counter, 20))
                {
                    smallestDivisible = Convert.ToString(counter);
                }
                else
                {
                    counter++;
                }
            }
            Console.WriteLine(smallestDivisible);
        }
Exemplo n.º 17
0
 /// <summary>
 ///		Updates the camera of the entity associated with this process.
 /// </summary>
 /// <param name="deltaTime">Elapsed time since last frame.</param>
 public override void Run(float deltaTime)
 {
     //if (_entity.IsEnabled == false) return;
     //if (_shakeIntensity <= 0)
     // {
     //    _shakeIntensity = 0;
     //    Finish(ProcessResult.Success);
     //}
     //else
     //    _shakeIntensity -= deltaTime;
     _entity.TransformationOffset = new Transformation(MathMethods.Random(-_shakeIntensity, _shakeIntensity),
                                                       MathMethods.Random(-_shakeIntensity, _shakeIntensity),
                                                       _entity.TransformationOffset.Z,
                                                       _entity.TransformationOffset.AngleX,
                                                       _entity.TransformationOffset.AngleY,
                                                       _entity.TransformationOffset.AngleZ,
                                                       _entity.TransformationOffset.ScaleX,
                                                       _entity.TransformationOffset.ScaleY,
                                                       _entity.TransformationOffset.ScaleZ);
 }
Exemplo n.º 18
0
        public static void DoMethod(int a, int b)
        {
            int caseSwitch;

            do
            {
                Console.WriteLine();
                Console.WriteLine("Select a mathematical operation:");
                Console.WriteLine("1 -> (+); 2 -> (-); 3 -> (*); 4 -> (/)");
                Console.WriteLine("Write (0) to close programm");
                caseSwitch = Convert.ToInt32(Console.ReadLine());
                switch (caseSwitch)
                {
                case 1:
                    Console.WriteLine("a + b = " + MathMethods.Summ(a, b));
                    break;

                case 2:
                    Console.WriteLine("a - b = " + MathMethods.Diff(a, b));
                    break;

                case 3:
                    Console.WriteLine("a * b = " + MathMethods.Multiplication(a, b));
                    break;

                case 4:
                    Console.WriteLine("a / b = " + MathMethods.Division(a, b));
                    break;

                case 0:
                    break;

                default:
                    Console.WriteLine("Operation does't exist");
                    break;
                }
            } while (caseSwitch != 0);
        }
Exemplo n.º 19
0
        /////

        protected override void OnMouseDown(MouseEventArgs e)
        {
            base.OnMouseDown(e);

            if (Manager.Room == null)
            {
                return;
            }

            Point snap = GetSnappedPoint(e.Location, new Size(_gridX / _zoom, _gridY / _zoom));

            // If mouse left button clicked.
            if (e.Button == MouseButtons.Left)
            {
                //Invalidate();
                _mouseX = snap.X;
                _mouseY = snap.Y;

                if (CurrentBrush == BrushMode.Move || CurrentBrush == BrushMode.Rotate)
                {
                    _drag = true;
                    if (CurrentBrush == BrushMode.Rotate)
                    {
                        Invalidate();

                        if (Manager.Project.SelectedInstance != null)
                        {
                            GmsRoomInstance p = Manager.Project.SelectedInstance;
                            this._rotateStart = MathMethods.PointDirection(p.x, p.y, _mx, _my);
                            Manager.MainWindow.statusLabelMousePos.Text = _rotateStart.ToString();
                        }
                    }

                    Manager.MainWindow.brushPlaceableUpdatePositionAndRotation();
                }
            }
        }
Exemplo n.º 20
0
 private bool isMultipleOf3And5(int a)
 {
     return(MathMethods.isMultipleOf(a, 3) || MathMethods.isMultipleOf(a, 5));
 }
Exemplo n.º 21
0
    public static void Main()
    {
        TestClass test = new TestClass();

        // Executing a method directly is pretty straight forward.
        // What if we don't want to execute these methods now,
        // but want to execute them when some event occurs?
        // This is where delegates come in.
        ImSpeakingNow("How are you?");
        MathMethods.MathSpeaks("I'm doing fine");

        // How did we get from methods to delegates to lambdas? How are they related?
        // We use delegates to reference any method that has a specific signature.
        // As long as the signatures match, we can reference any method
        // and execute it using the delegate.

        // Once upon a time you would create a delegate using object constructor syntax.
        // This creates a reference to a method, which can be executed at any time.
        SpeakDelegate        me   = new SpeakDelegate(ImSpeakingNow);
        SpeakDelegate        math = new SpeakDelegate(MathMethods.MathSpeaks);
        Action <string, int> xxx  = MathMethods.NewMethod;

        xxx("hello", 9);

        Action <string, int[]> newAction = MathMethods.NewMethod2;

        int[] myints = new int[] { 9, 8, 7 };
        newAction("I an another action", myints);

        Func <string, int, int> myFunc = MathMethods.myFunc;

        myFunc += MathMethods.myFunc2;
        int length = myFunc("Paul", 60);

        // Now execute the method you're referencing using the delegate it's mapped to.
        me("What a sunny day");
        math("I like to count");

        // Using the object constructor syntax was a little cumbersome, so
        // "implied conversion" was introduced. The compiler knows that
        // the method "TalkingTest" has the same signature as the SpeakDelegate
        // so it performs all the heavy lifting under the covers and allows
        // you to simply assign a method to a delegate.
        SpeakDelegate abc = test.TalkingTest;

        abc("I'm new");
        me = test.TalkingTest;

        // A Multicast Delegate is a delegate that holds the references of more than one function.
        // When a multicast delegate is executed, then all the functions which are referenced by
        // the delegate are going to be executed.
        me += ImSpeakingNow;
        me += MathMethods.MathSpeaks;

        // Notice that all 3 methods that this deletate references are executed with one line of code.
        // Also notice that all 3 methods are called synchronously!
        me("We're speaking the same language");

        // Example of passing a delegate as a parameter to a method
        ILikeDelegates(me, "All my delegates should say this");
        ILikeDelegates(ImSpeakingNow, "All my delegates should say this");

        // We can remove method references from the delegate to have as few or as many
        // references in the delegate that we want.
        me -= ImSpeakingNow;
        me -= MathMethods.MathSpeaks;

        me("Just me now");

        // Here are a couple more examples of using delegates
        MathMethods.DoMathDelegate doMath = test.AddThese;
        int Total = doMath(4, 8);

        Console.WriteLine($"Total of 4+8 = {Total}");

        // An "Action" is a predefined delegate that takes 0 or more parameters, does SOMETHING and returns void.
        // An Action can take no parameter or
        Action someAction = test.DoSomething;

        someAction();

        // Events help implement the "publisher/subscriber" model.
        // Any object can publish a set of events to which other objects can subscribe.
        // Let's say that we want to be notified whenever a method in the
        // TestClass class completes.  That class has an event called OperationCompleteEvent
        // that is fired to tell anyone listening about that event.
        test.OperationCompleteEvent += OnOperationComplete;

        // Now that our event has been hooked up, let's execute the same
        // code as before, but this time the events will fire and we will
        // be notified by having our event handlers called.
        doMath(4, 8);
        someAction();

        // Don't want to be notified of these events anymore
        test.OperationCompleteEvent -= OnOperationComplete;


        // There are many times when we want to execute code in some method
        // but it will only ever be called in one place. It seems like a
        // real waste to have to declare a method like we did
        // with "ImSpeakingNow(string SayThis)" just for that purpose.
        // To that end, the "Anonymous" method was created.
        // Anonymous methods provide a way to write unnamed inline
        // statement blocks that can be executed in a delegate invocation.

        List <String> names = new List <String>();

        names.Add("Fred");
        names.Add("Sam");
        names.Add("Bob");

        // The following demonstrates the anonymous method feature of C#
        // to display the contents of the list to the console
        names.ForEach(delegate(String name)
        {
            Console.WriteLine(name);
        });

        me = delegate(string Something) { Console.WriteLine($"Anonymous says: {Something}"); };
        me("I am here!");

        // A lambda expression is nothing more than syntactic sugar for an anonymous method.
        // The following lambda expression is EXACTLY the same as the anonymous method above.
        // The type of the parameter "Something" is inferred by the compiler.
        me = (Something) => { Console.WriteLine($"Lambda says: {Something}"); };
        me("I am here!");

        Func <int, int, int> ReturnSomething = (x, y) => { return(x + y); };
        int value = ReturnSomething(9, 8);

        Console.WriteLine($"Value is {value}");

        // The signature of the method called is:
        //      public static int Calculate(DoMathDelegate DoMath, int first, int second)
        //
        // The first parameter is a lambda expression matching the delegate signature:
        //		public delegate int DoMathDelegate(int first, int second)
        //
        // The next 2 parameters are the values consumed by the DoMathDelegate
        Console.WriteLine($"Value is {MathMethods.Calculate((a, b) => a + b, 1, 2)} using lambda");
        Console.WriteLine($"Value is {MathMethods.Calculate((x, z) => x * z, 1, 2)}");
        Console.WriteLine($"Value is {MathMethods.Calculate((q, r) => q - r, 1, 2)}");
        Console.WriteLine($"Value is {MathMethods.Calculate((f, h) => f / h, 1, 2)}");

        // Parameter delegates are often designed to work on data that is internal to the class/type.
        // The delegate is typically used to iterate over the internal data values to
        // produce some kind of result or filter the data in some way.
        MathMethods.AppendValue(2);
        MathMethods.AppendValue(3);
        MathMethods.AppendValue(4);
        MathMethods.AppendValue(5);
        MathMethods.AppendValue(6);
        MathMethods.AppendValue(7);
        MathMethods.AppendValue(8);
        Console.WriteLine($"CalculateTotal addition is {MathMethods.CalculateTotal((a, b) => a + b)}");
        Console.WriteLine($"CalculateTotal multiplication is {MathMethods.CalculateTotal((a, b) => a * b)}");


        // Here we will create a lambda expression that will be used to filter out all even numbers
        List <int> even = MathMethods.RunFilter(i => i % 2 == 0);

        foreach (int x in even)
        {
            Console.WriteLine($"Even {x}");
        }

        // Here we will create a lambda expression that will be used to filter out all odd numbers
        List <int> odd = MathMethods.RunFilter(i => i % 2 == 1);

        foreach (int x in odd)
        {
            Console.WriteLine($"Odd {x}");
        }

        /// A Predicate is a delegate like the Func and Action delegates.
        /// It represents a method that checks whether the passed parameter meets a set of criteria.
        /// A predicate delegate methods must take one input parameter and return a boolean - true or false.
        /// You'll find that built in delegate types like "Action", "Func<>" and "Predicate<>" can be used
        /// instead of creating your own custom delegates most of the time. Here's an example of using
        /// a built-in "Predicate<int>" instead of custom "FilterDelegate".
        List <int> lessThan5 = MathMethods.RunFilterPredicate(i => i < 5);

        Console.WriteLine($"Values less than 5 using predicate");
        foreach (int x in lessThan5)
        {
            Console.WriteLine($"{x}");
        }

        //----------------- What's happening under the hood? Expression Trees!
        System.Linq.Expressions.Expression <Func <int, int> > myExpression = x => x * x;
        string          lambdaString     = myExpression.ToString();
        Func <int, int> compiledDelegate = myExpression.Compile();
        int             parameter        = 8;
        int             answer           = compiledDelegate(parameter);

        Console.WriteLine($"Result of calling '{lambdaString}' using parameter '{parameter}' is '{answer}'");
        myExpression.DumpExpression();

        Expression <Func <int, bool> > expr = i => i % 2 == 0;

        expr.DumpExpression();
        Expression <Func <string, string, string> > tree = (a, b) => a.ToLower() + b.ToUpper();

        tree.DumpExpression();

        Expression <SpeakDelegate> myDelegate = (sayThis) => Console.WriteLine(sayThis);

        myDelegate.DumpExpression();

        FilmCritic.DemonstrateDeferredExecution("Rambo", "First", new DateTime(2009, 1, 1));



        List <string> listOfNames = new List <string>()
        {
            "John Doe",
            "Jane Doe",
            "Jenna Doe",
            "Joe Doe"
        };

        // Query syntax
        IEnumerable <string> qNames = from name in listOfNames where name.Length <= 8 select name;

        // Method syntax
        var mNames = listOfNames.Where(name => name.Length <= 8);

        // Representation of the query
        Expression <Func <IEnumerable <string>, IEnumerable <string> > > lambda = (myList) => from name in myList where name.Length <= 8 select name;

        lambda.DumpExpression();
        Console.WriteLine($"{lambda}");

        // Compile and Execute the query
        var compiledLinq = lambda.Compile();
        IEnumerable <string> expressionNames = compiledLinq(listOfNames);

        foreach (string x in expressionNames)
        {
            Console.WriteLine($"{x}");
        }
    }
Exemplo n.º 22
0
        public static StylusPointCollection GetRectangleCorner(StylusPointCollection collection)
        {
            double maxX = double.MinValue, minX = double.MaxValue, maxY = double.MinValue, minY = double.MaxValue;

            foreach (StylusPoint point in collection)
            {
                if (maxX < point.X)
                {
                    maxX = point.X;
                }
                if (minX > point.X)
                {
                    minX = point.X;
                }
                if (maxY < point.Y)
                {
                    maxY = point.Y;
                }
                if (minY > point.Y)
                {
                    minY = point.Y;
                }
            }

            double borderLength = MathMethods.GetDistanceBetTowPoints(maxX, maxY, minX, minY);

            if (borderLength < minRectangleBorder)
            {
                return(null);
            }


            double centerX      = (maxX + minX) / 2;
            double centerY      = (maxY + minY) / 2;
            double adjustWidht  = (maxX - minX) / 3;
            double adjustHeight = (maxY - minY) / 3;

            List <StylusPoint> topPoints    = new List <StylusPoint>();
            List <StylusPoint> bottomPoints = new List <StylusPoint>();
            List <StylusPoint> leftPoints   = new List <StylusPoint>();
            List <StylusPoint> rightPoints  = new List <StylusPoint>();

            foreach (var item in collection)
            {
                if (Math.Abs(item.X - centerX) > adjustWidht)
                {
                    if (item.X > centerX)
                    {
                        rightPoints.Add(item);
                    }
                    else
                    {
                        leftPoints.Add(item);
                    }
                }
                if (Math.Abs(item.Y - centerY) > adjustHeight)
                {
                    if (item.Y > centerY)
                    {
                        bottomPoints.Add(item);
                    }
                    else
                    {
                        topPoints.Add(item);
                    }
                }
            }

            double topAverage = 0.0;

            foreach (var point in topPoints)
            {
                topAverage += point.Y;
            }
            topAverage = topAverage / topPoints.Count;

            double bottomAverage = 0.0;

            foreach (var point in bottomPoints)
            {
                bottomAverage += point.Y;
            }
            bottomAverage = bottomAverage / bottomPoints.Count;

            double leftAverage = 0.0;

            foreach (var point in leftPoints)
            {
                leftAverage += point.X;
            }
            leftAverage = leftAverage / leftPoints.Count;

            double rightAvarage = 0.0;

            foreach (var point in rightPoints)
            {
                rightAvarage += point.X;
            }
            rightAvarage = rightAvarage / rightPoints.Count;
            StylusPointCollection corners = new StylusPointCollection();
            StylusPoint           one     = new StylusPoint(leftAverage, topAverage);
            StylusPoint           two     = new StylusPoint(rightAvarage, topAverage);
            StylusPoint           three   = new StylusPoint(rightAvarage, bottomAverage);
            StylusPoint           four    = new StylusPoint(leftAverage, bottomAverage);

            corners.Add(one);
            corners.Add(two);

            corners.Add(three);
            corners.Add(four);
            StylusPoint closedPoint = new StylusPoint(corners[0].X, corners[0].Y, 0.5f);

            corners.Add(closedPoint);
            return(corners);
        }
Exemplo n.º 23
0
        /// <summary>
        /// Get line corner
        /// </summary>
        /// <param name="collection">sample points</param>
        /// <param name="offset">0-100</param>
        /// <returns>line stylus points</returns>
        public static StylusPointCollection GetLineCorner(StylusPointCollection collection, double ratio = 1.5)
        {
            //y=a+bx;
            try
            {
                Debug.Assert(ratio > 1 && ratio < 25, "ratio should be in 1-25");
                Point  startPoint = collection[0].ToPoint();
                Point  endPoint   = collection[collection.Count - 1].ToPoint();
                double lineLength = MathMethods.GetDistanceBetTowPoints(startPoint.X, startPoint.Y, endPoint.X, endPoint.Y);
                if (lineLength < minLineLength)
                {
                    return(null);
                }

                double xAverage = 0.0;
                double yAverage = 0.0;
                double endX     = double.MinValue;
                double startX   = double.MaxValue;


                double b = 0.0;
                double a = 0.0;
                foreach (var point in collection)
                {
                    xAverage += point.X;
                    yAverage += point.Y;

                    if (endX < point.X)
                    {
                        endX = point.X;
                    }
                    if (startX > point.X)
                    {
                        startX = point.X;
                    }
                }

                xAverage = xAverage / collection.Count;
                yAverage = yAverage / collection.Count;

                double fenzi = 0.0;
                double fenmu = 0.0;
                foreach (var point in collection)
                {
                    fenzi += point.X * point.Y;
                    fenmu += point.X * point.X;
                }

                fenzi = fenzi - collection.Count * xAverage * yAverage;
                fenmu = fenmu - collection.Count * xAverage * xAverage;
                if (fenmu != 0)
                {
                    b = fenzi / fenmu;
                }
                double offset = ratio * lineLength / 100;
                if (fenmu == 0 || fenzi == 0 || Math.Abs(b) > 6)
                {
                    //vertical line

                    double startYtest     = double.MaxValue;
                    double endYtest       = double.MinValue;
                    int    unExpectPoints = 0;
                    foreach (var point in collection)
                    {
                        if (endYtest < point.Y)
                        {
                            endYtest = point.Y;
                        }
                        if (startYtest > point.Y)
                        {
                            startYtest = point.Y;
                        }

                        if (Math.Abs(xAverage - point.X) > offset * 2)
                        {
                            unExpectPoints++;
                        }
                    }
                    if (unExpectPoints > collection.Count / 4)
                    {
                        return(null);
                    }
                    StylusPointCollection result = new StylusPointCollection();
                    result.Add(new StylusPoint(xAverage, startYtest, 0.5f));
                    result.Add(new StylusPoint(xAverage, endYtest, 0.5f));
                    return(result);
                }
                else
                {
                    a = yAverage - b * xAverage;
                    int unExpectPoints = 0;
                    foreach (var point in collection)
                    {
                        double offsetY = a + b * point.X;
                        if (Math.Abs(offsetY - point.Y) > offset)
                        {
                            unExpectPoints++;
                        }
                    }
                    if (unExpectPoints > collection.Count / 5)
                    {
                        return(null);
                    }
                    double startY = a + b * startX;
                    double endY   = a + b * endX;
                    StylusPointCollection result = new StylusPointCollection();
                    result.Add(new StylusPoint(startX, startY, 0.5f));
                    result.Add(new StylusPoint(endX, endY, 0.5f));
                    return(result);
                }
            }
            catch (Exception ex)
            {
                Trace.WriteLine(ex.StackTrace);
#if DEBUG
                throw ex;
#else
                return(null);
#endif
            }
        }
Exemplo n.º 24
0
        //TempRes temp = new TempRes();
        public override ShrinkageResult[] Calculate(IRollLine line, IFilm film)
        {
            List <lengthsSector> lengthsSpectre = new List <lengthsSector>();

            Line  = line;
            IFilm = film;
            Rolls = line.WorkingRolls.ToList();
            var results = new List <ShrinkageResult>();

            Length[] ls    = new Length[Rolls.Count];
            var      L     = Ls().Select(x => x.l).ToArray();
            var      films = Films();
            //CalcCoveringAngles(ls, Rolls);
            var n   = IFilm.Material.GetScalarValue("n");
            var b   = IFilm.Material.GetScalarValue("b");
            var mu0 = IFilm.Material.GetScalarValue("mu0");
            var Tr  = IFilm.Material.GetScalarValue("Tr");

            var A = IFilm.Material.GetScalarValue("A_mr");
            var B = IFilm.Material.GetScalarValue("B_mr");
            var C = IFilm.Material.GetScalarValue("C_mr");

            var x1 = Math.Pow(2, n + 1);

            //////////

            /*
             * temp.AddStr("Расчет усадки полимерной пленки на базе модели Муни-Ривлина\r\n");
             * temp.AddStr("Индекс степенного закона = " + n.ToString() + "\r\n");
             * temp.AddStr("Температурный индекс = " + b.ToString() + ",1/С\r\n");
             * temp.AddStr("Коэффициент вязкости = " + mu0.ToString() + ",Па*с\r\n");
             * temp.AddStr("Температура приведения = " + Tr.ToString() + ",С\r\n");
             * temp.AddStr("");
             * temp.AddStr("Параметры тела Муни-Ривлина, эмпирические коэффициенты");
             * temp.AddStr("A = " + A.ToString() + "\r\n");
             * temp.AddStr("B = " + B.ToString() + "\r\n");
             * temp.AddStr("C = " + C.ToString() + "\r\n");*/
            //////////

            var gSum   = 0.0;
            var result = new List <double>();


            ///////
            //temp.AddStr("Валок\tТемпература\tВязкость\tНапряжение вытяжки\tПродольная усадка реологического тела Муни-Ривлина\r\n");
            double sumShrinkage = 0, goalShrinkage = 60;
            double sMin = 0, sMax = goalShrinkage * 1.5 / (Rolls.Count - 1);

            for (var i = 0; i < Rolls.Count - 1; ++i)
            {
                var currentRoll = Rolls[i];
                var nextRoll    = Rolls[i + 1];

                var currentFilm = films[i];
                var nextFilm    = films[i + 1];
                var x2          = Math.Pow((currentRoll.Velocity * n) / (L[i] * (1 - n)), n) * Math.Pow(2, n + 1);
                var x3          = Math.Pow(1 - currentRoll.Velocity / nextRoll.Velocity, 1 - n);
                var x4          = (currentFilm.Thickness * currentFilm.Width) / (nextFilm.Thickness * nextFilm.Width);
                var temperature = nextRoll.Temperature - Tr;
                var mu          = mu0 * Math.Exp(-b * temperature);
                var G           = x1 * x2 * x3 * x4 * mu;
                if (!double.IsNaN(G) && !double.IsInfinity(G))
                {
                    gSum = G;
                }
                const double step = 0.1;
                var          sum  = gSum;
                //AddStr("");
                //temp.AddStr(string.Format("\nПоиск корня уравнения: {0}*x^6 + {1}*x^4 + {2}*x^3 - {1}*x^2 - {3}", C, A, B - C - sum, B));
                //temp.AddStr(string.Format("\nна отрезке: [{0}; {1}]", sMin, sMax));
                //var root = MathMethods.ScanRoot(Sl => (C * Math.Pow(Sl, 6) + A * Math.Pow(Sl, 4) + (B - C - sum) * Math.Pow(Sl, 3) - A * Sl * Sl - B), sMin, sMax, 0.0001, 1000);
                var root = MathMethods.BisectRoot(Sl => (C * Math.Pow(Sl, 6) + A * Math.Pow(Sl, 4) + (B - C - sum) * Math.Pow(Sl, 3) - A * Sl * Sl - B), sMin, sMax, 0.0001, 100000);
                //AddStr("");
                //temp.AddStr(string.Format("\nF({0}) = {1}", root, (C * Math.Pow(root, 6) + A * Math.Pow(root, 4) + (B - C - sum) * Math.Pow(root, 3) - A * root * root - B)));

                //sMin += root;
                //sMax += root;
                int ind = 0;
                if (double.IsNaN(root))
                {
                    ind++;
                    break;
                }
                if (!double.IsNaN(root) && Math.Abs(Math.Round(root, 5) - 1) > 0.001)
                {
                    result.Add(root);
                }

                ///////
                //temp.AddStr((i + 1).ToString() + "\t\t" + temperature.ToString() + "С\t" + Math.Round(mu, 4).ToString() + "Па*с\t\t " + Math.Round(root, 4).ToString() + "\t\t" + Math.Round(G, 4) + "\t");
                ///////
                //results.Add(new ShrinkageResult(-result.Sum(x => (x)), ind, 0));
            }

            //////
            //AddStr("");
            //temp.AddStr("Усадка полимерной пленки");
            //temp.AddStr("Ширина\t\tДлина\t\tТолщина");

            /*foreach (var item in results)
             * {
             *  temp.AddStr(Math.Round(item.Sw, 5).ToString() + "% \t" + Math.Round(item.Sl, 5).ToString() + "% \t" + item.Sh.ToString() + "%");
             * }*/

            //temp.SaveToFile("D:\\" + ModelName + ".txt");
            ////////

            return(results.ToArray());
        }
Exemplo n.º 25
0
        public static StylusPointCollection GetTriangleCorner(StylusPointCollection collection)
        {
            try
            {
                #region get max values
                double maxX = double.MinValue, minX = double.MaxValue, maxY = double.MinValue, minY = double.MaxValue;
                foreach (StylusPoint point in collection)
                {
                    if (maxX < point.X)
                    {
                        maxX = point.X;
                    }
                    if (minX > point.X)
                    {
                        minX = point.X;
                    }
                    if (maxY < point.Y)
                    {
                        maxY = point.Y;
                    }
                    if (minY > point.Y)
                    {
                        minY = point.Y;
                    }
                }
                double borderLength = MathMethods.GetDistanceBetTowPoints(maxX, maxY, minX, minY);
                if (borderLength < minTriangleBorder)
                {
                    return(null);
                }

                List <double> data = new List <double>();
                data.Add(maxX);
                data.Add(minX);
                data.Add(maxY);
                data.Add(minY);
                #endregion

                #region Get bounds
                StylusPointCollection bounds = new StylusPointCollection();

                foreach (StylusPoint point in collection)
                {
                    bool isBound = data.Any(item => (item == point.X) || (item == point.Y));
                    if (isBound)
                    {
                        bounds.Add(point);
                    }
                }

                if (bounds.Count == 3)
                {
                    return(bounds);
                }
                #endregion

                StylusPointCollection pointsPre = new StylusPointCollection();
                StylusPoint           corner1   = bounds.FirstOrDefault(item => item.X == maxX); //1
                StylusPoint           corner2   = bounds.FirstOrDefault(item => item.Y == maxY); //2
                StylusPoint           corner3   = bounds.FirstOrDefault(item => item.X == minX); //3
                StylusPoint           corner4   = bounds.FirstOrDefault(item => item.Y == minY); //4
                corner1.PressureFactor = 0.5f;
                corner2.PressureFactor = 0.5f;
                corner3.PressureFactor = 0.5f;
                corner4.PressureFactor = 0.5f;
                if (corner1 != null)
                {
                    pointsPre.Add(corner1);
                }
                if (corner2 != null)
                {
                    pointsPre.Add(corner2);
                }
                if (corner3 != null)
                {
                    pointsPre.Add(corner3);
                }
                if (corner4 != null)
                {
                    pointsPre.Add(corner4);
                }
                if (pointsPre.Count > 3)
                {
                    //1,2,3;
                    double area1 = GetArea(corner1.X, corner1.Y, corner2.X, corner2.Y, corner3.X,
                                           corner3.Y);
                    //1,2,4
                    double area2 = GetArea(corner1.X, corner1.Y, corner2.X, corner2.Y, corner4.X,
                                           corner4.Y);

                    //1,3,4
                    double area3 = GetArea(corner1.X, corner1.Y, corner3.X, corner3.Y, corner4.X,
                                           corner4.Y);

                    //2,3,4
                    double area4 = GetArea(corner2.X, corner2.Y, corner3.X, corner3.Y, corner4.X,
                                           corner4.Y);
                    StylusPointCollection corners = new StylusPointCollection();
                    double maxArea = area1;
                    if (maxArea < area2)
                    {
                        maxArea = area2;
                    }
                    if (maxArea < area3)
                    {
                        maxArea = area3;
                    }
                    if (maxArea < area4)
                    {
                        maxArea = area4;
                    }
                    if (maxArea == area1)
                    {
                        corners.Add(corner1);
                        corners.Add(corner2);
                        corners.Add(corner3);
                    }
                    else if (maxArea == area2)
                    {
                        corners.Add(corner1);
                        corners.Add(corner2);
                        corners.Add(corner4);
                    }
                    else if (maxArea == area3)
                    {
                        corners.Add(corner1);
                        corners.Add(corner3);
                        corners.Add(corner4);
                    }
                    else//==area4
                    {
                        corners.Add(corner2);
                        corners.Add(corner3);
                        corners.Add(corner4);
                    }
                    StylusPoint closedPoint = new StylusPoint(corners[0].X, corners[0].Y, 0.5f);
                    corners.Add(closedPoint);
                    return(corners);
                }

                return(pointsPre);
            }
            catch (Exception ex)
            {
                Trace.WriteLine(string.Format("exception on find triangle is {0}", ex.StackTrace));
            }

            return(null);
        }
Exemplo n.º 26
0
 public void RandomA(ScriptThread thread)
 {
     thread.SetReturnValue(MathMethods.Random(thread.GetFloatParameter(0), thread.GetFloatParameter(1)));
 }
Exemplo n.º 27
0
        public static StylusPointCollection GetArrowCorner(StylusPointCollection collection, double ratio = 5)
        {
            try
            {
                StylusPointCollection corners = GetTriangleCorner(collection);
                if (corners != null && corners.Count == 4)
                {
                    StylusPoint first       = collection[0];
                    StylusPoint end         = collection[collection.Count - 1];
                    StylusPoint firstCorner = corners[0];
                    StylusPoint endCorner   = corners[1];

                    double minFistDis = double.MaxValue;
                    double minEndDis  = double.MaxValue;
                    foreach (StylusPoint point in corners)
                    {
                        double dis    = MathMethods.GetPowDistanceBetTowPoints(point.X, point.Y, first.X, first.Y);
                        double endDis = MathMethods.GetPowDistanceBetTowPoints(point.X, point.Y, end.X, end.Y);

                        if (minFistDis > dis)
                        {
                            minFistDis  = dis;
                            firstCorner = point;
                        }

                        if (minEndDis > endDis)
                        {
                            minEndDis = endDis;
                            endCorner = point;
                        }
                    }

                    StylusPoint centerCorner = corners.FirstOrDefault(item => item != firstCorner && item != endCorner);
                    if (centerCorner != null && centerCorner.X > 0 && centerCorner.Y > 0)
                    {
                        double cf = MathMethods.GetDistanceBetTowPoints(centerCorner.X, centerCorner.Y, firstCorner.X, firstCorner.Y);
                        double ce = MathMethods.GetDistanceBetTowPoints(centerCorner.X, centerCorner.Y, endCorner.X, endCorner.Y);

                        double cf_ce = Math.Abs(cf - ce);
                        if (cf_ce > 150)
                        {
                            return(null);
                        }
                        double fe = MathMethods.GetDistanceBetTowPoints(firstCorner.X, firstCorner.Y, endCorner.X, endCorner.Y);
                        // cosA = (c^2 + b^2 - a^2) / (2·b·c)
                        double cosA = (cf * cf + ce * ce - fe * fe) / (2 * cf * ce);
                        if (cosA < 0.04 || cosA > 0.93)
                        {
                            return(null);
                        }

                        #region Check bound is two line
                        //Get line one function
                        double line1K = (centerCorner.Y - firstCorner.Y) / (centerCorner.X - firstCorner.X);
                        double line1A = line1K;
                        double line1B = -1;
                        double line1C = centerCorner.Y - line1K * centerCorner.X;

                        //Get line two function
                        double line2K = (centerCorner.Y - endCorner.Y) / (centerCorner.X - endCorner.X);
                        double line2A = line2K;
                        double line2B = -1;
                        double line2C = centerCorner.Y - line2K * centerCorner.X;

                        int line1Count = 0;
                        int line2Count = 0;

                        double lineDis1    = MathMethods.GetDistanceBetTowPoints(centerCorner.X, centerCorner.Y, firstCorner.X, firstCorner.Y);
                        double lineDis2    = MathMethods.GetDistanceBetTowPoints(centerCorner.X, centerCorner.Y, endCorner.X, endCorner.Y);
                        double line1offset = lineDis1 * ratio / 100;
                        double line2offset = lineDis2 * ratio / 100;
                        for (int i = 0; i < collection.Count; i++)
                        {
                            double dis1 = MathMethods.GetDistanceBetPointToLine(collection[i].X, collection[i].Y, line1A, line1B, line1C);


                            if (dis1 < line1offset)
                            {
                                line1Count++;
                            }
                            else
                            {
                                double dis2 = MathMethods.GetDistanceBetPointToLine(collection[i].X, collection[i].Y, line2A, line2B, line2C);
                                if (dis2 < line2offset)
                                {
                                    line2Count++;
                                }
                            }
                        }

                        if (collection.Count - (line1Count + line2Count) > collection.Count / 20)
                        {
                            return(null);
                        }
                        #endregion

                        StylusPoint maxDisPoint  = firstCorner;
                        StylusPoint minDisPoint  = endCorner;
                        double      maxDisCenter = cf;
                        double      minDisCenter = ce;
                        if (cf < ce)
                        {
                            maxDisPoint  = endCorner;
                            minDisPoint  = firstCorner;
                            maxDisCenter = ce;
                            minDisCenter = cf;
                        }

                        //line:y=a+bx;
                        double b = (maxDisPoint.Y - centerCorner.Y) / (maxDisPoint.X - centerCorner.X); //(y1-y2)/(x1-x2)
                        double a = 0 - b * centerCorner.X + centerCorner.Y;                             //-b*x1+y2

                        double startTest   = Math.Min(maxDisPoint.X, centerCorner.X);
                        double endTest     = Math.Max(maxDisPoint.X, centerCorner.X);
                        Point  targetPoint = new Point(maxDisPoint.X, maxDisPoint.Y);

                        for (double i = startTest; i < endTest; i += 1)
                        {
                            double y   = a + b * i;
                            double dis = MathMethods.GetDistanceBetTowPoints(i, y, centerCorner.X, centerCorner.Y);
                            if (Math.Abs(minDisCenter - dis) <= 5)
                            {
                                targetPoint.X = i;
                                targetPoint.Y = y;
                                break;
                            }
                        }

                        if (targetPoint.X <= 0 || centerCorner.X <= 0)
                        {
#if DEBUG
                            throw new Exception("targetPoint.X should noe be zero");
#endif
                        }
                        StylusPointCollection result = new StylusPointCollection();

                        result.Add(new StylusPoint(targetPoint.X, targetPoint.Y, 0.5f));
                        result.Add(centerCorner);
                        result.Add(minDisPoint);

                        return(result);
                    }
                }
            }
            catch (Exception ex)
            {
                Trace.WriteLine(ex.StackTrace);
#if DEBUG
                throw ex;
#endif
            }
            return(null);
        }
Exemplo n.º 28
0
 public void RandomB(ScriptThread thread)
 {
     thread.SetReturnValue(MathMethods.Random(thread.GetIntegerParameter(0), thread.GetIntegerParameter(1)));
 }
        public void GetFactorial_GivenNumber_ReturnsExpectedNumber(int number, int expected)
        {
            var result = MathMethods.GetFactorial(number);

            Assert.Equal(expected, result);
        }
Exemplo n.º 30
0
 public void SeedRandom(ScriptThread thread)
 {
     MathMethods.SeedRandom(thread.GetIntegerParameter(0));
 }