简体   繁体   English

用bash计算功率

[英]Calculating the power in bash

I'm pretty new to bash scripting. 我很擅长bash脚本。 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. 我正在尝试计算出来,而我特别想要做的是编写一个允许我输入参数的脚本,并且我的脚本计算出该参数的2的幂。

So say I would try 所以说我会尝试

bash scriptname 3

My script would calculate 2^3=8 我的脚本会计算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 ** bash中的幂运算符是**

Example: 例:

echo $((2 ** 4))
16

It is worth pointing out that you'd observe overflow when the result starts to exceed LONG_MAX : 值得指出的是,当结果开始超过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) (当值超过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 (它也允许你使用^ !):

$ 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): 只是为了好玩,你也可以使用按位移位(当然这只适用于功率为2的基数):

echo $((1<<$1))

Make sure you read devnull's caveat about overflows. 请务必阅读devnull关于溢出的警告。

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. 如果您需要这样的非整数运算,则可以使用bc实用程序。 eg if you need to take the 3rd power of 2.5, you can do this: 例如,如果您需要获得2.5的3次幂,您可以这样做:

$ 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. 注意设置scale builtin变量设置应该给出的小数位数计算。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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