I was trying to raise an integer to a power using the caret operator (^
), but I am getting surprising results, e.g.:
assert_eq!(2^10, 8);
How can I perform exponentiation in Rust?
Fractional exponents Taking a number to the power of 12 undoes taking a number to the power of 2 (or squaring it). In other words, taking a number to the power of 12 is the same thing as taking a square root: x1/2=√x.
Rust provides exponentiation via methods pow
and checked_pow
. The latter guards against overflows. Thus, to raise 2 to the power of 10, do:
let base: i32 = 2; // an explicit type is required assert_eq!(base.pow(10), 1024);
The caret operator ^
is not used for exponentiation, it's the bitwise XOR operator.
Here is the simplest method which you can use:
let a = 2; // Can also explicitly define type i.e. i32 let a = i32::pow(a, 10);
It will output "2 raised to the power of 10", i.e.:
1024
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With