Package term02.m04_d27

Source Code of term02.m04_d27.BinarySearch

package term02.m04_d27;

import term02.m04_d27.functions.ExponentialFunction;
import term02.m04_d27.functions.Function;

public class BinarySearch {

    public static void main(String[] args) {
        Function f = new ExponentialFunction();

        System.out.println(searchRoot(f, 1));
        System.out.println(searchRoot(f, Math.E));
    }

    private static double findLeftBound(Function function, double constant) {
        double result = -1;

        while (function.getValue(result) > constant) {
            result *= 2;
        }

        return result;
    }

    private static double findRightBound(Function function, double constant) {
        double result = 1;

        while (function.getValue(result) < constant) {
            result *= 2;
        }

        return result;
    }

    private static double searchRoot(Function function, double constant) {
        double left = findLeftBound(function, constant);
        double right = findRightBound(function, constant);

        while (left < right - Function.EPS) {
            double mid = (left + right) / 2;

            if (function.getValue(mid) < constant) {
                left = mid;
            } else if (function.getValue(mid) > constant) {
                right = mid;
            } else {
                return mid;
            }
        }

        return left;
    }
}
TOP

Related Classes of term02.m04_d27.BinarySearch

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.