|
1 | 1 | //! Approximation calculations
|
2 | 2 |
|
3 | 3 | use {
|
4 |
| - num_traits::{CheckedAdd, CheckedDiv, One, Zero}, |
5 |
| - std::cmp::Eq, |
| 4 | + num_traits::{CheckedShl, CheckedShr, PrimInt}, |
| 5 | + std::cmp::Ordering, |
6 | 6 | };
|
7 | 7 |
|
8 |
| -const SQRT_ITERATIONS: u8 = 50; |
9 |
| - |
10 |
| -/// Perform square root |
11 |
| -pub fn sqrt<T: CheckedAdd + CheckedDiv + One + Zero + Eq + Copy>(radicand: T) -> Option<T> { |
12 |
| - if radicand == T::zero() { |
13 |
| - return Some(T::zero()); |
| 8 | +/// Calculate square root of the given number |
| 9 | +/// |
| 10 | +/// Code lovingly adapted from the excellent work at: |
| 11 | +/// https://github.com/derekdreery/integer-sqrt-rs |
| 12 | +/// |
| 13 | +/// The algorithm is based on the implementation in: |
| 14 | +/// https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Binary_numeral_system_(base_2) |
| 15 | +pub fn sqrt<T: PrimInt + CheckedShl + CheckedShr>(radicand: T) -> Option<T> { |
| 16 | + match radicand.cmp(&T::zero()) { |
| 17 | + Ordering::Less => return None, // fail for less than 0 |
| 18 | + Ordering::Equal => return Some(T::zero()), // do nothing for 0 |
| 19 | + _ => {} |
14 | 20 | }
|
15 |
| - // A good initial guess is the average of the interval that contains the |
16 |
| - // input number. For all numbers, that will be between 1 and the given number. |
17 |
| - let one = T::one(); |
18 |
| - let two = one.checked_add(&one)?; |
19 |
| - let mut guess = radicand.checked_div(&two)?.checked_add(&one)?; |
20 |
| - let mut last_guess = guess; |
21 |
| - for _ in 0..SQRT_ITERATIONS { |
22 |
| - // x_k+1 = (x_k + radicand / x_k) / 2 |
23 |
| - guess = last_guess |
24 |
| - .checked_add(&radicand.checked_div(&last_guess)?)? |
25 |
| - .checked_div(&two)?; |
26 |
| - if last_guess == guess { |
27 |
| - break; |
| 21 | + |
| 22 | + // Compute bit, the largest power of 4 <= n |
| 23 | + let max_shift: u32 = T::zero().leading_zeros() - 1; |
| 24 | + let shift: u32 = (max_shift - radicand.leading_zeros()) & !1; |
| 25 | + let mut bit = T::one().checked_shl(shift)?; |
| 26 | + |
| 27 | + let mut n = radicand; |
| 28 | + let mut result = T::zero(); |
| 29 | + while bit != T::zero() { |
| 30 | + let result_with_bit = result.checked_add(&bit)?; |
| 31 | + if n >= result_with_bit { |
| 32 | + n = n.checked_sub(&result_with_bit)?; |
| 33 | + result = result.checked_shr(1)?.checked_add(&bit)?; |
28 | 34 | } else {
|
29 |
| - last_guess = guess; |
| 35 | + result = result.checked_shr(1)?; |
30 | 36 | }
|
| 37 | + bit = bit.checked_shr(2)?; |
31 | 38 | }
|
32 |
| - Some(guess) |
| 39 | + Some(result) |
33 | 40 | }
|
34 | 41 |
|
35 | 42 | #[cfg(test)]
|
|
0 commit comments