Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@Tosainu
Created July 12, 2019 14:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Tosainu/9ee4b0c4502635357687502253b270eb to your computer and use it in GitHub Desktop.
Save Tosainu/9ee4b0c4502635357687502253b270eb to your computer and use it in GitHub Desktop.
fn binary_sqrt(n: f64, tol: f64) -> f64 {
let mut s = 1.0f64;
let mut e = n;
while (s.powi(2) - n).abs() > tol {
let m = (s + e) / 2.0;
if m.powi(2) > n {
e = m;
} else {
s = m;
}
}
s
}
fn main() {
for i in 1..50 {
let fi = i as f64;
println!("{}: {:16.12} {:16.12}", i, binary_sqrt(fi, 1e-8), fi.sqrt());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment