Micheal O'Dwyer
Micheal O'Dwyer

Reputation: 1261

How to raise an integer to a signed integer power in Rust?

I've been using the pow() method on integers. I tried raising a u32 to a negative power, which resulted in an compile error.

fn main() {
    println!("{}", 2u32.pow(-1));
}
error[E0600]: cannot apply unary operator `-` to type `u32`
 --> src/main.rs:2:29
  |
2 |     println!("{}", 2u32.pow(-1));
  |                             ^^

This makes perfect sense, because the pow() function does not take a signed integer as a parameter.

Is there any way to raise an integer to a signed integer power, ideally without using an experimental nightly API? Is there any reason to only allow for unsigned integers as parameters to the pow() function?

I expect that the result would be 0.5, and the type would be a float. I now see that a function which allows for this probably cannot be called directly on the unsigned integer, because that would result in its type changing.

Perhaps there is a function which then takes both the base and power as an argument and returns a float, if such a function cannot be called directly on the integer?

Upvotes: 6

Views: 4680

Answers (1)

Shepmaster
Shepmaster

Reputation: 430564

I expect that the result [...] type would be a float

There is no float type in Rust. If you refer back to The Rust Programming Language, specifically the chapter on data types, you'll see that there are two built-in floating point types: f32 and f64. Which of those should this proposed method return?

I expect that the result would be 0.5

(2u32 as f32).powi(-1)
(2u32 as f64).powi(-1)

if such a function cannot be called directly on the integer

Any method can be called as a function:

f32::powi(2u32 as f32, -1)
f64::powi(2u32 as f64, -1)

See also:

Upvotes: 6

Related Questions