Calculator in terminal linux

GNU bc — калькулятор командной строки для Linux

Оригинал: What is a good command-line calculator on Linux
Автор: Dan Nanni
Дата публикации: 21 октября 2014 года
Перевод: А. Кривошей
Дата перевода: октябрь 2015 г.

Любой современный дистрибутив Linux включает графический калькулятор. С другой стороны, если вашим обычным рабочим окружением является терминал, то вы скорее будете искать себе калькулятор, который бы работал в командной строке. В этой категории программ, по моему мнению, единоличным лидером является GNU bc (сокращение от «basic calculator»). Это очень мощная и полезная утилита.

Еще до наступления эры GNU, bc исторически был известным языком для вычислений, первая реализация которого относится к старым добрым временам Unix 70-х годов. Изначально bc был больше известен в качестве языка программирования с синтаксисом, похожим на C. Со временем оригинальный bc эволюционировал в POSIX bc, а затем и в GNU bc.

Возможности GNU bc

Сегодняшний GNU bc является результатом многочисленных усовершенствований предыдущих реализаций, и сегодня он представляет собой стандарт для всех главных дистрибутивов GNU/Linux. bc поддерживает стандартные арифметические операции с числами произвольной точности и различных систем счисления (двоичные, десятеричные, шестнадцатеричные).

Если вы знакомы с языком C, вы увидите, что в bc используются те же или похожие математические операторы. Среди поддерживаемых операций арифметические (+,-,*,/,%,++,—), сравнения ( ,==,!=, =), логические (!,&&,||), побитовые (&,|,^,

, >), составного присваивания (+=,-=,*=,/=,%=,&=,|=,^=,&&=,||=, >=). bc имеет много полезных встроенных функций, таких как извлечение квадратного корня, тригонометрические и обратные тригонометрические функции, логарифмы, экспонента и так далее.

Использование GNU bc

Возможности GNU bc как калькулятора командной строки практически неограничены. В этом руководстве я собираюсь описать самые популярные функции bc. Получить полную информацию о возможностях программы можно из официальной документации.

За исключением случая запуска ранее написанного скрипта, обычно bc используется в интерактивном режиме, где каждая строка, содержащая выражение или оператор, интерпретируется и выполняется на лету. Чтобы перейти в интерактивную сессию bc, введите приведенную ниже команду. Для выхода из сессии введите «quit» и нажмите Enter.

Во всех приведенных в данном руководстве примерах подразумевается, что они вводятся внутри сессии bc.

Типы выражений

Для расчета арифметического выражения просто введите выражение и нажмите Enter. Если хотите, можете сохранить промежуточный вариант в переменной, чтобы затем использовать его в других выражениях.

В пределах одной сессии bc сохраняет всю историю введенных строк. Для возврата к предыдущим выражениям используется курсорная клавиша со стрелкой вверх. Если вы хотите ограничить число строк, сохраняемых в истории, присвойте нужное вам число переменной по имени history. По умолчанию ее значение -1, что соответствует «unlimited».

Читайте также:  Сеть windows через debian

Переключение между системами счисления ввода/вывода

Часто может потребоваться вводить числа и выводить на экран результаты в двоичном или шестнадцатеричном формате. Для этого bc позволяет определить систему счисления для ввода и вывода. Они хранятся в переменных ibase и obase соответственно. По умолчанию значение этих специальных переменных равно 10, а диапазон допустимых значений от 2 до 16 (или значения переменной окружения BC_BASE_MAX в случае obase). Все, что вам нужно для смены системы счисления — изменить значения ibase и obase. Например, ниже пример суммирования двух шестнадцатеричных/двоичных чисел:

Обратите внимание, что я задал сначала obase=16, затем ibase=16, а не наоборот. Если бы задал сначала ibase=16, то выражение obase=16 интерпретировалось бы уже в шестнадцатеричном формате (то есть мы присваивали бы obase значение 22 в десятеричной форме).

Точность

В bc точность чисел хранится в специальной переменной под названием scale (количество десятичных цифр после точки). По умолчанию ее значение равно 0, что соответствует хранению всех цифр результата. Вы можете изменить точность, присвоив перменной scale соответствующее значение.

Использование встроенных функций

Помимо простых арифметических операций GNU bc предлагает большой набор продвинутых математических функций, как встроенных, так и находящихся во внешней математической библиотеке. Для использования этих функций запустите bc с опцией «-l».
Ниже проиллюстрированы некоторые из этих встроенных функций.

Квадратный корень из N:

Синус от X (X в радианах):

Косинус от X (X в радианах):

Арктангенс от X (возвращаемое значение в радианах):

Натуральный логарифм от X:

Экспонента от X:

Другие возможности языка

GNU bc поддерживает простые операторы (например присваивание значения переменной, break, return), составные операторы (if, while, for loop), и функции, определенные пользователем. Я не буду детально описывать эти возможности, но вы легко можете научиться пользоваться ними из официального руководства. Ниже пример определения очень простой функции:

Неинтерактивное использование GNU bc

До сих пор мы использовали bc в интерактивном режиме. Однако достаточно часто он используется неинтерактивно, в скриптах оболочки. В этом случае вы можете направить ввод на bc с помощью команды echo, например:

В завершение можно сказать, что GNU bc — это очень мощный гибкий калькулятор командной строки, который соответствует самым высоким требованиям. Предустановленный во всех современных дистрибутивах Linux, bc может значительно упростить ваши задачи, не выходя из терминала.

Источник

How to use Calculator in Linux command line

As a Linux administrator you might use the command line calculator many times in a day for doing some math, using bc command.

I used the bc command several times while creating LVM to calculate PE values.

The command line calculator will allow us to perform all kinds of operations such as scientific, financial, or even simple calculation. Also, it can be used in shell scripts for complex math.

This article describes best five commands to perform your calculations using the terminal. They are listed below:

  • bc : Basic calculatoer used for basic math.
  • calc : It’s alternative to bc.
  • gcalccmd : is the console version of Gnome Calculator utility.
  • qalc : is the console version of the calculator app of Qalculate.
  • expr& echo : Linux command is used for very basic math calculation.

1) How to perform calculation in Linux using bc command?

bs stands for ‘Basic Calculator’. It offers you everything you would expect from a scientific, financial, or even simple calculator.

Читайте также:  Как завести будильник windows 10

bc is a language that supports arbitrary precision numbers with interactive execution of statements. There are some similarities in the syntax to the C programming language.

By default bc command is pre-installed in all the Linux systems. If not, use the following commands to install it depending on your environment:

1.a) How to use bc command

Simply type «bc» on your terminal to launch the bc command and use the following symbols for calculation:

  • Plus : Addition
  • Minus : Subtraction
  • Forward Slash : Division
  • Asterisk: Used for Multiplication

Type ‘quit’ to exit the bc once you’re done.

Use “ -l ” flag to define the standard math library:

2) How to use the Linux terminal as a Calculator with calc command?

calc is an arbitrary precision calculator that comes with a rich set of built-in mathematical and programmatic functions.

It’s a simple calculator that allow us to perform all kinds of calculation in Linux command line, which is not pre-installed and you need to use the below commands to install it.

For “Fedora” & “RHEL/CentOS 8” systems, use dnf command to install calc :

For “Debian/Ubuntu” based systems, use apt command to install calc :

For “Arch Linux” based systems, use pacman command to install calc :

For “RHEL/CentOS 6/7” systems, use yum command to install calc :

For “openSUSE Leap” system, use zypper command to install calc :

2.a) Calculations with calc command

It’s an alternative to bc and can be used for any kind of mathematical calculation right from the terminal, as shown below.

Interactive mode:

Non-Interactive mode:

3) How to perform calculation in Linux using gcalccmd command?

gnome-calculator is the official calculator of the GNOME desktop environment, whereas ‘gcalccmd’ is the console version of Gnome Calculator utility. By default it has installed in the GNOME desktop, no matter your distro.

3.a) gcalccmd command to perform calculation

I have added few examples on this, and this can do calculations similar to other command line calculators mentioned above.

Note: To exit from the gcalccmd command, press “Ctrl+d” or enter “quit”

4) How to perform calculation in Linux using qalc command?

Qalc is the console version of the calculator app of Qalculate, which is used as multi-purpose calculator. It is simple to use but provides versatile features.

If you are looking for a calculator with some extra features like currency conversion, percentage calculation and unit calculations, Qalc will meet your needs.

4.a) qalc command to perform calculation

I have added few examples below to demo this:

5) How to perform basic calculation in Linux using expr & echo command?

If you just want to perform basic calculations, then you don’t need to install any calculator application on your system. You can do them in bash shell using expr & echo commands.

Both are included in the “coreutils” package, which is pre-installed almost on all Linux distributions.

5.a) expr command to perform calculation

Use the following format for basic calculations.

For addition, subtraction & division

For multiplication: The ‘backslash’ should be added before the asterisk :

5.b) echo command to perform calculation

Wrapping Up

We’ve shown you how to use the Linux terminal as a calculator, regardless of your distro.

Читайте также:  Arch linux статический ip

If you found this article helpful, please do share with your friends and spread the knowledge. Please feel free to comment below if you have any queries/concerns. We will get back to you as soon as we can. Happy learning!

Источник

How To Use Calculator In Linux Command Line?

Short Bytes: You can use the Linux terminal to do mathematical calculations using command line calculator utilities. This includes the inbuilt gcalccmd and GNU bc. Qalculator, a third party utility is also a good command line calculator.

T he calculator is a hell lot of a handy app because it’s hard for us to get our brains at work. Some calculator apps are intelligent, and some of them are dumb af. However, that’s a different topic of discussion we can have some other day. This article describes some tools which allow you to use the calculator from the command line in Linux distros.

gcalccmd

It is the console version of Gnome Calculator utility present in Linux distributions like Ubuntu. To use the gcalccmd calculator tool, type the following command in the terminal:

Do the calculations

Performing calculations is simple. Just enter the numbers and desired operators in the terminal and press Enter. You can also use brackets in your calculations.

You can find the square root, natural log, etc:

You can also find sine, cosine, tangent values for given angles:

Press CTRL+D to exit from the gcalccmd tool and still remain on the command line. You can access the help section by using the help command inside gcalccmd.

Qalc is the terminal version of the calculator app, Qalculate. It doesn’t come pre-installed like gcalccmd. The command line calculator also allows you to do currency conversions besides regular calculation work.

You can install Qalc using the following command in the terminal:

After installation, if it fails to update currency exchange rates, then you can do so by following the steps below:

In the terminal, type qalc and press enter. To update the currency exchange rates, type exrates and press enter.

You can use the qalc command to start Qalculate on the command line. You can do the currency conversion as follows:

You can do unit conversion along with regular calculation stuff. Also, it remembers the answer from your last calculation. So, you can go like this:

Press CTRL+D to exit qalc command line calculator utility. You can access the help section by using the help command inside the qalc utility.

GNU bc

GNU bc is a command line calculator utility that is used for regular as well as scientific calculations in the command line.

How to install GNU bc?

Just like gcalccmd, bc is also present in your Linux distro.

Using bc

You can do calculations similar to the other command line calculators mentioned above.

These were some of the command line calculator utilities you can use on the Linux terminal. To know more about these utilities, you can visit their man pages.

If you have something to add, tell us in the comments below.

Источник

Оцените статью