Search code examples
rustnth-root

Taking n-th root


What is the best way to take the n-th root of an arbitrary number in rust? The num crate for example only allows to take n-th principal roots of integer types, i.e., floor'ed or ceil'ed values... How to best closely approximate the actual value?


Solution

  • Mathematically, nth root is actually 1 / n power to the number.

    You can use f64::powf(num, 1.0 / nth) to calculate such roots.

    fn main(){
        println!("{:?}", f64::powf(100.0, 1.0 / 3.0));
        // same as cbrt(100), cube root of 100
        // general formula would be
        // f64::powf(number, 1.0 / power)
    }
    

    You can use f32::powf also, there's no problem with it.