简体   繁体   中英

Calculating the power in bash

I'm pretty new to bash scripting. I'm trying to work out calculations, and what I'm specifically trying to do is write a script that allows me to enter a parameter, and that my script calculates the power of 2 to that parameter.

So say I would try

bash scriptname 3

My script would calculate 2^3=8

I'm trying with

(( 2 ^ $1 ))

but that's not doing anything. Is there a command to calculate the power of something that I'm not aware of?

The power operator in bash is **

Example:

echo $((2 ** 4))
16

It is worth pointing out that you'd observe overflow when the result starts to exceed LONG_MAX :

$ echo $((2**62))
4611686018427387904
$ echo $((2**63 - 1))
9223372036854775807
$ echo $((2**63))
-9223372036854775808

(Observe the result when the value exceeds 2 63 -1)

You might instead want to use something that allows arbitrary precision arithmetic since you might hit that limit rather fast if computing powers. For example, you could use bc (and it'd let you use ^ too!):

$ bc <<< 2^63
9223372036854775808
$ bc <<< 2^128
340282366920938463463374607431768211456
$ BC_LINE_LENGTH=0 bc <<< 2^1024
179769313486231590772930519078902473361797697894230657273430081157732675805500963132708477322407536021120113879871393357658789768814416622492847430639474124377767893424865485276302219601246094119453082952085005768838150682342462881473913110540827237163350510684586298239947245938479716304835356329624224137216

Just for fun you can also use bitwise shifts (of course this only works for a base that is a power of a power of 2):

echo $((1<<$1))

Make sure you read devnull's caveat about overflows.

The other answers are entirely correct, and if you are working with integer values represent the best way to do this kind of calculation. But it is worth noting that arithmetic does not deal with non-integer values.

If you require non-integer arithmetic like this, you can use the bc utility. eg if you need to take the 3rd power of 2.5, you can do this:

$ bc <<< "scale=10; 2.5 ^ 3"
15.625
$ 

Note setting the scale builtin variable sets the number of decimal places calculations should be given in.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM