2

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?

Chayim Friedman
  • 47,971
  • 5
  • 48
  • 77
D3PSI
  • 154
  • 2
  • 11

1 Answers1

7

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.

Darth-CodeX
  • 2,166
  • 1
  • 6
  • 23