MCPcopy Create free account
hub / github.com/douchuan/algorithm / sqrt_newton

Function sqrt_newton

src/math/mysqrt.rs:22–40  ·  view source on GitHub ↗
(x: f64)

Source from the content-addressed store, hash-verified

20}
21
22pub fn sqrt_newton(x: f64) -> f64 {
23 assert!(x >= 0.0);
24 if x == 0.0 {
25 return x;
26 }
27 if (x - 1.0).abs() <= f64::EPSILON {
28 return 1.0;
29 }
30 let mut last = 0.0;
31 let mut iter_v = x;
32 loop {
33 // iter_v = iter_v - (iter_v * iter_v - x) / (2.0 * iter_v);
34 iter_v = (iter_v + x / iter_v) / 2.0; //由上式化简得来
35 if (iter_v - last).abs() <= f64::EPSILON {
36 return iter_v;
37 }
38 last = iter_v;
39 }
40}
41
42// exp(log(x) * 0.5)
43pub fn sqrt3(x: f64) -> f64 {

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected