I'm trying to find the square root of a number (num
) using binary search in Rust. I'm new to Rust, but I've done quite a bit of programming in other languages, though. I'm more interested in how to generally improve this, as I'm not familiar with Rust best-practices and simaler than I am about the algorithm, although I don't mind advice on that*. Here's how this generally works:
- Take the number we're trying to find the root of
- Set
current_guess
to 1/2 of the number to take the square root of - While
current_guess
squared is not within a specifiedtolorance
, repeat the following steps until it is within the desiredtolorance
: - Calculate the difference between the current guess squared and the input number. That is how far off our number squared is from the target number
- If our number squared is within the tolorance, done. Else, if our number is two low, multiply it by
1.5
to make it bigger. If it is too high, divide it by two. Repeat until solved.
And of course the code. It is ran with a normal cargo run
.
fn main() {
println!("The square root of 16129 is approximately {}", sqrt(16129.0, 0.01));
}
fn sqrt(num: f64, tolorance: f64) -> f64 {
// the number we will try next
let mut current_guess = num / 2.0;
// how far off our current guess is
let mut current_difference: f64;
loop {
current_difference = current_guess.powi(2) - num;
if current_difference.abs() <= tolorance {
// if our answer is within the accepted tolorance range
return current_guess;
} else if current_difference < tolorance {
// if our current guess is too small
current_guess *= 1.5;
} else if current_difference > tolorance {
// if our current guess is too big
current_guess *= 0.5;
}
}
}
The current output of my code is
Compiling square-root v0.1.0 (C:\[redacted]\square-root)
Finished dev [unoptimized + debuginfo] target(s) in 1.65s
Running `target\debug\square-root.exe`
127.00000413730865
And that is the right answer. Of course, I could make it more precise by making the tolerance smaller. *I have nothing against making that part better, just my goal was to get a feel for Rust more than finding square roots. So I'm more interested in good ways to improve the code, but I don't mind critiques of the algorithm.