Accord.Math.Optimization.BinarySearch.Find C# (CSharp) Method

Find() public static method

Finds a value of a function in the interval [a;b]
public static Find ( double>.Func function, int lowerBound, int upperBound, double value ) : int
function double>.Func The function to have its root computed.
lowerBound int Start of search region.
upperBound int End of search region.
value double The value to be looked for in the function.
return int
        public static int Find(Func<int, double> function, int lowerBound, int upperBound, double value)
        {
            int start = lowerBound;
            int end = upperBound;

            int m = (int)(((long)start + (long)end) / 2);
            double v = function(m);

            while (end >= start)
            {
                if (v < value)
                {
                    start = m + 1;
                }
                else if (v > value)
                {
                    end = m - 1;
                }
                else
                {
                    return m;
                }

                m = (int)(((long)start + (long)end) / 2);
                v = function(m);
            }

            if (v > value || m == upperBound)
                return m;
            return m + 1;
        }

Same methods

BinarySearch::Find ( double value ) : int

Usage Example

Example #1
0
        public void ConstructorTest1()
        {
            Func<int, double> function = x => elements[x];
            BinarySearch search = new BinarySearch(function, 0, elements.Length);

            int a1 = search.FindRoot();
            Assert.AreEqual(1, a1);

            for (int i = 0; i < elements.Length; i++)
            {
                int a2 = search.Find(elements[i]);
                Assert.AreEqual(i, a2);
            }
        }
All Usage Examples Of Accord.Math.Optimization.BinarySearch::Find