如何使用 bash shell 计算功率值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18093424/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 06:10:03  来源:igfitidea点击:

how to compute power value with bash shell

bashshell

提问by Eman

We want to calculate 2^(3.0) and 2^(-3.0). thanks.

我们要计算 2^(3.0) 和 2^(-3.0)。谢谢。

!/bin/bash
c=3.0
g=-3.0
c=$((2**$c)) #syntax error: invalid arithmetic operator (error token is ".0")
g=$((2**$g)) #syntax error: invalid arithmetic operator (error token is ".0")
echo "c=$c"
echo "g=$g"

回答by Keith Thompson

Bash's built-in arithmetic only operates on integers, and doesn't allow a negative exponent for the **operator.

Bash 的内置算术只对整数进行运算,并且不允许**运算符使用负指数。

There are a variety of other tools available that can perform floating-point arithmetic. For example:

有多种其他工具可以执行浮点运算。例如:

$ c=3.0
$ g=-3.0
$ awk "BEGIN{print $c ** $c}"
27
$ awk "BEGIN{print $c ** $g}"
0.037037
$ perl -e "print $c ** $c, qq(\n), $c ** $g, qq(\n)"
27
0.037037037037037

To store the result in a variable:

要将结果存储在变量中:

$ c=$(awk "BEGIN{print $c ** $c}")
$ echo $c
27

回答by Thamme Gowda

Good answers already in the thread using perl and awk. We can also use python:

使用 perl 和 awk 的线程中已经有很好的答案。我们也可以使用python:

python -c "from sys import argv as a; print(pow(int(a[1]), int(a[2])))" 2 6

For reuse:

重用:

alias pow='python -c "from sys import argv as a; print(pow(int(a[1]), int(a[2])))"'
pow 2 6
pow 2 -2

回答by James White

#!/bin/bash
for (( i=1; i<257; i++ ))
  do
    h=`echo  2^"$i" |bc -l`;
    echo -e -n $i "  " '\t'
    echo  $h  |tr -d -c [0-9] |rev |sed -e 's/\([0-9][0-9][0-9]\)/,/g' |rev | sed 's/^,//';
  done
exit 0