Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to raise a number to a power?

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?

like image 531
Matthias Braun Avatar asked Jul 06 '18 10:07

Matthias Braun


People also ask

How do you raise a number to the 1 2 power?

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.


2 Answers

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.

like image 71
Matthias Braun Avatar answered Sep 30 '22 12:09

Matthias Braun


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

like image 38
Rohan Avatar answered Sep 30 '22 14:09

Rohan