コード例 #1
0
        private static double BinarySearchInternal(double left, double right, ExaminedDoubleFunction function, bool ascendingFunction, params object[] hiddenParams)
        {
            for (; ; )
            {
                double middlePoint = (left + right) / 2.0f;
                if ((middlePoint <= left) || (middlePoint >= right))
                    return middlePoint;

                double middleValue = function(middlePoint, hiddenParams);
                if (ascendingFunction)
                {
                    if (Math.Sign(middleValue) < 0)
                        left = middlePoint;
                    else
                        right = middlePoint;
                }
                else
                {
                    if (Math.Sign(middleValue) > 0)
                        left = middlePoint;
                    else
                        right = middlePoint;
                }
            }
        }
コード例 #2
0
        /// <summary>
        /// Binary search algorithm to search for solution of f(x) = 0.
        /// </summary>
        /// <param name="left">Left start point.</param>
        /// <param name="right">Right start point.</param>
        /// <param name="function">Delegate of the function f.</param>
        /// <param name="hiddenParams">Parameters to be passed to the examinated function f.</param>
        /// <returns>The point between left and right start point, where f(x) = 0.</returns>
        public static double BinarySearch(double left, double right, ExaminedDoubleFunction function, params object[] hiddenParams)
        {
            // check arguments
            if (left >= right)
                throw new ArgumentException("The left point must be less than the right point.");

            // verify the left and right points
            double leftValue = function(left, hiddenParams);
            double rightValue = function(right, hiddenParams);
            bool ascendingFunction = (rightValue > leftValue);
            if (Math.Sign(leftValue) == Math.Sign(rightValue))
                throw new ArgumentException("The function must have different signs at the left and right points.");

            // it is ok to start now...
            return BinarySearchInternal(left, right, function, ascendingFunction, hiddenParams);
        }