From d35aa4e7b23a0ecb7bdacf4e6941e17417fb2be6 Mon Sep 17 00:00:00 2001 From: Devdutt Shenoi Date: Sat, 21 Mar 2020 09:12:23 +0530 Subject: [PATCH] Add newton-raphson method to find sqrt --- .../number_theory/newton_raphson_sqrt.rs | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 src/algorithms_data_structures/number_theory/newton_raphson_sqrt.rs diff --git a/src/algorithms_data_structures/number_theory/newton_raphson_sqrt.rs b/src/algorithms_data_structures/number_theory/newton_raphson_sqrt.rs new file mode 100644 index 0000000..0dfc029 --- /dev/null +++ b/src/algorithms_data_structures/number_theory/newton_raphson_sqrt.rs @@ -0,0 +1,28 @@ +// Implementing Newton Raphson method to find square root +fn sqrt(x:f64, y:u8)-> f64 { + let mut r = x.clone(); + + match (x < 0.0, y > 11) { + (false, false) => { + + // Set precision + let precision:f64 = 10f64.powi(-1*(y as i32)); + + while (x - r * r).abs() > precision { + r = (r + x / r) / 2.0; + } + } + (true, false) => panic!("Trying to find imaginary roots!"), + (false, true) => panic!("Trying to find root of too much precision!"), + (true, true) => panic!("Trying to find imaginary roots to a very large precision!") + }; + + r +} + +fn main() { + // Test with a random value + let i = 3.14; + let j = 3; + println!("The square root of {} for {} decimal places is: {}", i, j, sqrt(i as f64, j)); +}