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?
Asked
Active
Viewed 674 times
1 Answers
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
-
1ah yes of course. thanks for the hint :) wasn't aware you could simply pass the reciprocal of n into that as the exponent – D3PSI May 24 '22 at 19:15
-
@D3PSI Not a problem – Darth-CodeX May 25 '22 at 13:17