二分法开根号的Rust实现
fn sqrt(x: f64) -> f64 {
let mut low: f64 = 0.0;
let mut up: f64 = x;
let mut mid: f64 = x / 2.0;
let mut result: f64 = mid * mid;
loop {
// println!("low = {}, up = {}, mid = {}", low, up, mid);
if low == up || mid == low || mid == up {
break;
}
if result > x {
up = mid;
mid = (low + up) / 2.0;
result = mid * mid;
} else if result < x {
low = mid;
mid = (low + up) / 2.0;
result = mid * mid;
} else {
break;
}
}
mid
}