fadedbee
fadedbee

Reputation: 44739

Raising an integer to a fractional power

I have the code:

(i as f64).powf(2.0 / 5.0).floor() as u64

Is there a way of raising an integer to a fractional power without resorting to floating point?

(I could performing two separate integer power operations. It would either overflow or lose a lot of precision, depending on the order.)

Upvotes: 3

Views: 874

Answers (1)

L. F.
L. F.

Reputation: 20579

Using the num crate to avoid precision loss:

use num::{BigUint, ToPrimitive};

BigUint::from(base)
    .pow(exp_num)
    .nth_root(exp_den)
    .to_u64() // `.try_into()` works too -- import `TryInto` instead of `ToPrimitive`
    .expect("result overflows u64")

(playground)

To achieve full accuracy, there isn't much you can do other than using big integers, so go for it if you really need the precision. Do watch out for performance though — this calculation is quite expensive when the numerator or denominator of the exponent is large.

Upvotes: 3

Related Questions