[Java學習]二分法找真值

mldlx發表於2015-01-07
<pre name="code" class="java">public class Test {
	public static void printOut(double num, double c) {
	  System.out.println("the true value is " + num + ".");
		System.out.println("the estimate value is " + c + ".");
	}
	
	public static double search(double num, double a, double b) {
		if(a >= b) {
			double temp = a;
			a = b;
			b = temp;
		}
		double c = (a + b)/2;
		if(num > c){
			a = c;
		}
		else if(num < c) {
			b = c;
		}
		else {
			printOut(num, c);
			return c;
		}
		if((b - a) >= 1E-5){
			return search(num, a, b);
		}
		else {
			printOut(num, c);
			return c;
		}
	}

	public static void main(String[] args) {
		search(14.34, 10, 20);
	}
}