web-dev-qa-db-ja.com

Ubuntu用のコマンドライン電卓はありますか?

他の余分な接頭辞や接尾辞なしで端末自体で計算を実行できる計算機を探しています。

例:ターミナルで10000-9000のように入力すると、答えは1000になります。

繰り返しになりますが、文字を追加することなく、ターミナルに簡単な電卓が必要です。 Pythonに切り替えた場合、それができることは知っていますが、そのようにしたくありません。

119
rɑːdʒɑ

バッシュ算術

別の可能な解決策は、Bashの組み込み演算用の単純な関数を追加することです。これを.bashrcファイルに入れて試してください:

=() {
    echo "$(($@))"
}

そのため、今では$((...))は必要なく、=だけで十分です。

置換

さらに高速にしたい場合は、p+に、x*に置き換えることもできます。これはそのために動作します:

=() {
    local IFS=' '
    local calc="${*//p/+}"
    calc="${calc//x/*}"
    echo "$(($calc))"
}

= 5 x 5  # Returns 25
= 50p25  # Returns 75

今は必要ありません Shift もはや、算術の前にあるのはだけです。

16進出力

必要に応じて、出力を10進数と16進数の両方で表示できます。 (x置換を使用すると、0x... hex構文と競合します)

=() {
    local answer="$(($@))"
    printf '%d (%#x)\n' "$answer" "$answer"
}

例:

$ = 16 + 0x10
272 (0x110)

$ = 16**3 + 16**4
69632 (0x11000)

bcを使用

少し高度な計算が必要な場合は、次のようにbcにパイプできます。

=() {
    local IFS=' '
    local calc="${*//p/+}"
    calc="${calc//x/*}"
    bc -l <<<"scale=10;$calc"
}

= 'sqrt(2)' # Returns 1.4142135623
= '4*a(1)'  # Returns pi (3.1415926532)

bcで提供される関数は次のとおりです(man bcから見つけることができます):

sqrt ( expression )
       The value of the sqrt function is the square root of the expression.  
       If the expression is negative, a run time error is generated.

s (x)  The sine of x, x is in radians.

c (x)  The cosine of x, x is in radians.

a (x)  The arctangent of x, arctangent returns radians.

l (x)  The natural logarithm of x.

e (x)  The exponential function of raising e to the value x.

j (n,x)
       The Bessel function of integer order n of x.

また、ifforwhileおよびプログラミング言語のような変数もサポートしていますが、必要に応じてファイルに書き込む方が良い場合もあります。

関数/変数名のpxを置換することに注意してください。単に置換を削除する方が良い場合があります。

gcalccmdを使用

次のように、関数呼び出しをgcalccmdgnome-calculatorから)することもできます。

=() {
    local IFS=' '
    local calc="$*"
    # Uncomment the below for (p → +) and (x → *)
    #calc="${calc//p/+}"
    #calc="${calc//x/*}"
    printf '%s\n quit' "$calc" | gcalccmd | sed 's:^> ::g'
}

= 'sqrt(2)' # Returns 1.4142135623
= '4^4'     # Returns 256

使用可能な関数は( ソースコード から直接取られている)ようで、==は同等の関数を示します。

ln()
sqrt()
abs()
int()
frac()
sin()
cos()
tan()
sin⁻¹() == asin()
cos⁻¹() == acos()
tan⁻¹() == atan()
sinh()
cosh()
tanh()
sinh⁻¹() == asinh()
cosh⁻¹() == acosh()
tanh⁻¹() == atanh()
ones()
twos()
78
kiri

((...))構文を使用して、bashでネイティブに単純な整数演算を実行できます。

$ echo $((10000-9000))
1000

標準入力で算術式を受け入れることができるbc計算機もあります

$ echo "10000-9000" | bc
1000

bcプログラムは、浮動小数点演算も実行できます

$ echo "scale = 3; 0.1-0.09" | bc
.01
93
steeldriver

calc を使用できます。デフォルトではインストールされませんが、次のコマンドを使用してすばやくインストールできます。

Sudo apt-get install apcalc

インストール後、希望する計算を実行できます。

$ calc 5+2
    7
$ calc 5-2
    3
$ calc 5*2          
    10
$ calc 5/2
    2.5
$ calc 5^2
    25
$ calc 'sqrt(2)' 
    1.4142135623730950488
$ calc 'sin(2)'
    0.9092974268256816954
$ calc 'cos(2)'
    -0.416146836547142387
$ calc 'log(2)'
    ~0.30102999566398119521
$ calc 'sqrt(sin(cos(log(2))))^2'
    ~0.81633199125847958126
$ # and so on...

詳細については、 man-page をご覧ください

90
Radu Rădeanu

残念ながら、これを行うための「簡単な」方法はありません。 apcalc \とは異なり、Ubuntuではpythonincludedであるため、コマンドラインの対話型pythonインターフェイスは必要なものに最適です。 bcがまだ含まれているかどうかはわかりませんが、pythonがこのようなものに好評です。

コマンドラインでインタラクティブなpythonインターフェースを実行し、そのように計算することができます。これを計算機として使用できます。

これを行うには、ターミナルを開き、pythonと入力してから、 Enter ボタン。

次に、表示されるpythonプロンプトで、数学を入力できます。たとえば、10000 - 9000。次の行の出力は結果です。


ただし、ターミナルをロードするだけでこれを実行できる場合は...

$ 10000-9000 
 1000 
 $

...それでは、justでこれを行う方法はありません。Bashはそのような数値引数を処理しないためです。

30
Thomas Ward

基本的なPython計算のための簡単な関数を作成することをお勧めします。 .bashrcで次のようなもの:

calc() {
    python3 -c 'import sys; print(eval(" ".join(sys.argv[1:])))' "$@"
}

calc 5 + 5
# Returns 10

result="$(calc 5+5)"
# Stores the result into a variable

より高度な数学を実行したい場合は、mathモジュールのすべての関数をインポートする次のものを使用できます。 (詳細については here を参照)

calc() {
    python3 -c 'from math import *; import sys; print(eval(" ".join(sys.argv[1:])))' "$@"
}

calc 'sqrt(2)'  # Needs quotes because (...) is special in Bash
# Returns 1.4142135623730951

result="$(calc 'sqrt(2)')"
# Stores the result into a variable

(注:Pythonはプログラミング言語であるため、例えば、べき乗の**やモジュロの%など、奇妙に思われることもあります)

または、Pythonスクリプトcalcを作成できます。

#!/usr/bin/python3
from math import *
import sys
print(eval(' '.join(sys.argv[1:])))

PATH変数に含まれるディレクトリに配置し、その実行可能フラグを設定して上記と同じcalcコマンドを取得します(Pythonスクリプトを実行するためにBash関数を作成する必要はありません) )。

純粋なBashでメソッドが必要な場合は、steeldriverの答えを使用してください。 PythonはBashと比べて比較的遅いため、この答えは、より高度な機能(つまり、mathから)が必要な場合にのみ有益です。


これがあなたの「pythonへの切り替え」を破るかどうかはわかりませんが、そうすることができます。そのような方法でそれを望んでいません。ただし、インタラクティブなプロンプトを入力する必要はなく、結果はBashでアクセスできるため、この回答は(少なくとも私には)有効なようです。

23
kiri

gnome-calculator(> = 13.04)またはgcalccmd(<13.04)パッケージのgcalctoolを使用します。パッケージはデフォルトでインストールされていると思います

% gcalccmd
> 2+3
5
> 3/2
1.5
> 3*2
6
> 2-3
−1
> 
21
Flint

以下に、このための簡単なシェルスクリプトを示します。

#!/bin/bash
echo "$@" | bc

これを「c」として保存し、パスのどこかに(/ binなど)配置し、実行可能としてマークします。

# nano /bin/c
# chmod +x /bin/c

これから、次のように端末で計算を実行できます。

$ c 10000-9000
1000
10
user530873

不明なコマンドの最初の文字が数字または/etc/bash.bashrcまたはcommand_not_foundである場合、-ハンドラーを変更してシェルの式エバリュエーターを実行する+(Ubuntu 10.04上)の適切な部分の変更を次に示します。

この方法でシェルの算術演算を行うことができます。算術演算子のリストについては、 http://www.gnu.org/software/bash/manual/bashref.html#Shell-Arithmetic を参照してください。

評価する式に*が含まれている場合、実行するコマンドを決定する前にシェルがファイル名の展開を行うため、*\または引用符で囲む必要があることに注意してください。 >>のような他の演算子にも同じことが言えます。

これを~/.bashrcに入れてから、. ~/.bashrcと入力して試してください。

# if the command-not-found package is installed, use it
if [ -x /usr/lib/command-not-found -o -x /usr/share/command-not-found ]; then
    function command_not_found_handle {
        if [[ $1 == [0-9+-]* ]]; then
           echo $(( $@ ))
        Elif [ -x /usr/lib/command-not-found ]; then
           /usr/bin/python /usr/lib/command-not-found -- $1
           return $?
        Elif [ -x /usr/share/command-not-found ]; then
           /usr/bin/python /usr/share/command-not-found -- $1
           return $?
        else
           return 127
        fi
    }
fi

サンプル出力:(新しいcommand_not_foundハンドラーがまだ不明なコマンドを検索しようとしていることをテストするために、タイプミスとしてctaと入力しています)。

mp@ubuntu:~$ cta
No command 'cta' found, did you mean:
 Command 'cda' from package 'xmcd' (universe)
 Command 'cat' from package 'coreutils' (main)
cta: command not found
mp@ubuntu:~$ 9000-1000
8000
8
Mark Plotnick

私がここで言及していない別の解決策は、Qalculate(qalc)です。

Sudo apt-get install qalc

cLIバージョンの場合、

Sudo apt-get install qalculate-gtk

gUI用。

次のような多くの機能があります。

  • unitsのサポート:例20 m / s * 12 h = 864 kilom
  • piecavogadroなどの組み込み定数
  • 多くの組み込み関数:例sin(pi) = 0gamma(4) = 65! = 120log(1024, 2) = 10
  • 単位変換、例:

> 120 in
120 * inch = 120 in
> convert cm
120 in = 304.8 centim

  • シンボリック計算、例えば(x + y)^2 = x^2 + 2xy + y^2
  • 統合、例えばintegrate 3*x^2 = x^3diff sin(x), pi
  • 組み込みヘルプ、例えばhelp converthelp integrate
  • コマンドのタブ補完
  • すべてが翻訳されます。私のシステムはオランダ語なので、factorial(5)faculteit(5)の両方を書くことができます。
  • もっと...

あなたは接頭辞なしでそれを使いたいと言います、まあ...あなたは接頭辞付きでそれを使うことができます:

$ qalc 5 ft + 3 cm
(5 * foot) + (3 * centim) = 1.554 m

また、replとして実行します。

8
JW.

dc!これはcoreutilsの一部であるため、OS X、Ubuntu、およびその他すべてにインストールされます。これはRPN計算機であるため、それらが気に入らなければ、あなたのためではありません。

非常に基本的なコマンドは次のとおりです(マンページには、私が含めなかったすべての構文があります。べき乗、だれでも?)

数字の間にスペースのみが必要です。それ以外の場合は無視されます。

数字を入力すると、その数字がスタックの一番上にプッシュされます。

+ Adds top 2 items in stack, then pushes result to stack (`2 4 +p` outputs 6)
- Subtracts top 2 items in stack, then pushes result to stack (`4 2 -p` outputs 2)
* Multiplies top 2 items in stack, then pushes result to stack (`6 5 *p` outputs 30)
/ Divides top 2 items in stack, then pushes result to stack (`54 7 /p` outputs 8)
p Print top item in stack, without destroying it
c Clear stack
r Swap top 2 items on stack
d Duplicate top item on stack
k Pops top item off stack, using it to determine precision (so 10 k would print 10 numbers after the decimal point). Default is 0, so it won't do floating point math by default.
n Pops top value off stack, then sends to stdout without a trailing newline
f Dump stack. Useful for finding what something does
7

私はこの種のことのためにOctaveを使用しています: http://www.gnu.org/software/octave/

オクターブを入力することで端末で使用できるmatlabクローン(これが過度に単純化されている場合は謝罪)です。 Sudo apt-get install octaveをインストールします

それはあなたが望むものではありませんが、私はPythonの代替としてそれを追加すると思いました。

使用例:

~ $ octave
octave:1> 9000 - 8000
ans =  1000
octave:2> 
5
Andy T

私はwcalcがとても好きです。これはコマンドライン関数電卓です。 Ubuntu Software Centerで簡単に見つけるか、apt-getを使用するだけです。

Sudo apt-get install wcalc

コマンドライン引数を受け入れ、「シェル」モードがあります:

# simple operation
$ wcalc 2+2
 = 4
# Quoting is necessary to prevent Shell from evaluating parenthesis
$ wcalc "(2+2)*10"                                                                                    
 = 40
$ wcalc "sqrt(25)"                                                                                    
~= 5
# in Shell mode you can evaluate multiple commands repeatedly
$ wcalc
Enter an expression to evaluate, q to quit, or ? for help:
-> 12*20+1
 = 241
-> sin(90)
 = 1
-> sin(pi/2)
 = 0.0274121

そして、誰かが私のようにエンジニアリングに携わっている場合、GNU Octaveを使用できます。グラフ化、連立方程式の解法など、あらゆることが可能です。さらに、Matlabの無料の代替品です

5

簡単な方法はpythonを呼び出すことです。

例:

>  python -c 'print 10000-9000'
4
user2327875

私が見つけたのは、expr、bc、または組み込みのシェルオプションが信頼できないことです。したがって、私は通常* linux distroにインストールされるPerlを使用しました

Perl -le 'printf "%.0f", eval"@ARGV"' "($VAL2-$VAL1)"

上記の計算では、$ VAL2から$ VAL1が減算され、小数点以下の桁なしで印刷されます(0f)

Perlを使用する利点は( 長所と短所をここにリスト )の詳細)

  • エラーキャプチャの改善(0で除算しても計算は停止しません)
  • 構成ファイルで式を提供できます。複雑な正規表現を使用してエスケープする必要はありません
3
diaryfolio

次の関数を.bashrcファイルに追加できます。

function = {
  echo "$@" | bc -l
}

-lフラグは非常に重要です。それがなければ、bcを使用すると5 / 2 = 2が得られます。

上記のメンチオ化されたため、式の前に=記号を使用して計算を行うことができます。

3
vdm

また、 awk を使用して、端末でいくつかの算術計算を行うこともできます。

echo 10000 9000 | awk '{print $1-$2}'
1000
echo 10000 9000 | awk '{print $1+$2}'
19000
echo 10000 9000 | awk '{print $1/$2}'
1.11111
echo 10000 9000 | awk '{print $1*$2}'
90000000
3
Avinash Raj

過去に、私は wcalc と、eと呼ばれる小さなプログラムを使用しましたが、グーグルで検索するのはほとんど不可能です。これを行うには、pythonスクリプトを使用します。これは、角括弧のようなeの機能を使用します。 wcalcは、任意の精度と単位変換を行うことができるため、依然として素晴らしいですが、私はこれらの機能をほとんど使用しません。

#!/usr/bin/env python3

"""
This is a very simple command line calculator.  It reads in all
arguments as a single string and runs eval() on them.  The math module
is imported so you have access to all of that.  If run with no
arguments, it allows you to input a single line expression.  In the
case of command line args, square brackets are replaced with round
parentheses, because many shells interpret round parentheses if they
are not quoted.
"""

import sys, numbers
import cmath, math

args = sys.argv[1:]

if len(args) < 1:
    expr = input()
else:
    expr = " ".join(args[:])
    expr = expr.replace("[", "(").replace("]", ")")

def log2(x):
    """Return the base-2 logarithm of x."""
    return cmath.log(x, 2)

# the smallest number such that 1+eps != 1
# (this is approximate)
epsilon = sys.float_info.epsilon

env = math.__dict__
env.update(cmath.__dict__)
env = {k:v for k,v in env.items() if not k.startswith("__")}
env["eps"] = epsilon
env["log2"] = log2
env["inf"] = float("inf")
env["nan"] = float("nan")

res = eval(expr, env)
# throw away small imaginary parts, they're probably just due to imprecision
if (isinstance(res, numbers.Number)
    and res != 0
    and abs(res.imag)/abs(res) < 10*epsilon):
    res = res.real

print(str(res).replace("(", "[").replace(")", "]"))

使用方法は次のとおりです(スクリプトがeとして保存され、$PATHのどこかに配置されていると仮定):

$ e e**[pi*1i]
-1.0
$ e hex[10**3]
0x3e8
$ e "[0o400+3]&0xff" # need quotes because of '&'
3
2
jpkotta

「bc」コマンドを使用すると、uは計算を実行できます

[root@vaibhav ~]# bc

----------these lines will genrate automaicaly---------------

right 1991-1994, 1997, 1998, 2000, 2004, 2006 Free Software Foundation, Inc.
This is free software with ABSOLUTELY NO WARRANTY.
For details type `warranty'. 

---------------enter your calculation here---------------------------------------


10+2   

12

保証書なしでbcを使用するには、ターミナルbc -qに書き込みます

[root@vaibhav ~]# bc -q
10+2
12
2
Vaibhav Jain

Bindとbashを使用できます C-a そして C-e 出力を制御します。たとえば、シェルでこれを実行します。

bind '"\C-j": "\C-aecho $(( \C-e )) \C-m"'

次に、10 + 15などの算術演算を入力して、 Ctrl+J

$ echo $(( 10 + 15 )) 
25

これを取得します。さて、それはどのように行われますか?

  • bindこのコマンドは、ショートカットキーのように、bashのバインドを変更します。
  • \C-jこれは、Ctrl + Jに相当するbashです。これは、コマンドに追加するキーの組み合わせです。
  • \C-aこれにより、行の先頭に移動します。
  • echo $((これは、開始時にecho $((を書き込みます。
  • \C-eは行末まで連れて行ってくれます
  • ))は前の括弧を閉じます
  • \C-mこれは、リターンキーと同等です。

これを~/.inputrcファイルに書き込むことができます:

"\C-j": "\C-aecho $(( \C-e )) \C-m"

もちろん、他の答えも有効です!少し調整しました。

  • bc:"\C-j": "\C-aecho " \C-e " | bc \C-m"
  • apcalc:"\C-j": "\C-acacl \C-m"
  • python:"\C-j": "\C-apython3 -c "print( \C-e )" \C-m"
  • 他のもの?

Ctrl + Jを好きなように変更できますが、既にバインディングが設定されているものは変更しないでください;)。

資源:

2
Braiam

printf Shellビルトインを使用して、端末で算術計算を行うこともできます。

printf `expr $num1 + $num2`   # num1,num2 are  variables which stores numbers as values.

例:

$ printf "$(expr 10000 + 9000)\n"
19000
$ printf "$(expr 10000 - 9000)\n"
1000
0
Avinash Raj

ターミナル計算機を作成する

以下を.bashrcファイルに入れます

function calc
{
 echo "${1}"|bc -l;
}

または、シェルプロンプトで実行します。これで、シェルの「calc」は次のように機能します。

$ calc 3+45
   48

「(」または「)」の付いたすべての関数は引用符で囲む必要があります。

0
Vishnu N K

あなたが望むものを正確に達成するためのワンステップの方法があります。必要なことは、アカウントのShell/bin/bcに設定することだけです。

0
bizzyunderscore

pythonインタープリターを使用して計算できます。 これを行う方法に関するチュートリアルです

Python 2およびpython 3は、デフォルトでUbuntuにインストールされます。

$ python
Python 2.7.12 (default, Nov 19 2016, 06:48:10) 
[GCC 5.4.0 20160609] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 2+2
4
>>> 3*5
15
0
noone