Arbitrary Precision Integer Arithmetic within the Bourne Once more Shell (BASH)

This can be a transient submit on fast methods to carry out arbitrary precision integer arithmetic within the GNU Bourne Once more Shell (BASH), both on the command immediate or in a shell script. It’s partially a followup to the submit Floating Level Arithmetic within the Bourne Once more Shell (BASH) and overlaps a number of the content material on this earlier submit.

The Bourne Once more Shell, or bash, is the default command line processor (shell) for Mac OS X, the cygwin atmosphere on MS Home windows, and plenty of different Unix and Unix-like methods. Particularly in the event you work with numbers, chances are you’ll need to carry out fast arbitrary precision arithmetic on the command immediate (shell) or in shell scripts. This submit covers 3 ways to carry out arbitrary precision arithmetic in bash: the bc arbitrary precision calculator language, the python programming language, and the ruby programming language.

Arbitrary Precision Arithmetic

Most computer systems and pc programming languages in addition to calculator applications default to thirty-two (32) or sixty-four (64) bit integers or floating level numbers. This restricts the vary of integers that may be represented and computed appropriately with integer numbers and restricts the vary and precision of floating level numbers. For instance, an unsigned 32 bit integer can solely signify the numbers from zero (0) to 4,294,967,296 (two raised to the thirty second energy, considerably over 4 billion.) An unsigned 64 bit integer can solely signify the numbers from zero (0) to 18,446,744,073,709,551,616 (two raised to the sixty fourth energy, considerably over eighteen quintillion).

These enormous numbers, particularly for sixty-four bit integer and floating level numbers, are far past our on a regular basis expertise, however they are often encountered in public key cryptography which entails merchandise of big integers, in computing factorials which develop quickly, in astronomy or physics, and in numerous different specialised purposes and fields. Factorials come up continuously in likelihood and statistics. Twenty-one factorial (21! in frequent mathematical notation) is 51,090,942,171,709,440,000 (over fifty-one quintillion) which is simply too massive for an unsigned 64-bit integer.

Arbitrary precision arithmetic is usually slower than the usual integer or floating level arithmetic on most computer systems which make the most of {hardware} arithmetic designed for the usual 32 and 64 bit numbers, nevertheless it lacks the vary and precision limitations of the usual 32 and 64 bit numbers and arithmetic.

Three Methods to Carry out Arbitrary Precision Integer Arithmetic in BASH

(1) BC

The next instructions present easy methods to increase two to an arbitrary energy, an instance of arbitrary precision arithmetic, on the bash shell immediate utilizing the bc arbitrary precision calculator language. Observe the necessity to enclose the arithmetic expression in single quotes. Observe using the backtick MYVAR=`command` syntax to assign the outcomes of the arithmetic to a bash variable.

Additionally, notice that bc makes use of the caret ^ for elevating to an influence, not two asterisks — 2**128 for instance — as in lots of pc languages together with python and ruby mentioned beneath.

Observe that there must be no area between the variable title and the equal signal within the task, in any other case an error happens.


bash$ echo '2^128' | bc -l
340282366920938463463374607431768211456

bash$ MYVAR=`echo '2^128' | bc -l`
bash$ echo $MYVAR
340282366920938463463374607431768211456


BC could be run interactively by typing:


bash$ bc -l
bc 1.06
Copyright 1991-1994, 1997, 1998, 2000 Free Software program Basis, Inc.
That is free software program with ABSOLUTELY NO WARRANTY.
For particulars sort `guarantee'. 
2^128
340282366920938463463374607431768211456


BC doesn’t have a built-in factorial operate however one could be outlined:

factorial


outline factorial (n) { 
  if (n < 0) {
    print "ERROR: argument is lower than zero";
    halt;
  }
  if (n < 2) return 1;
  return n*factorial(n-1);
}

The file factorial above with the definition of the factorial operate could be handed to bc on the command line:


bash$ bc -l factorial
factorial(21)
51090942171709440000
factorial(1)
1
factorial(0)
1
factorial(-1)
ERROR: argument is lower than zero

The factorial could be computed on the bash command line as follows:


bash$ echo 'factorial(21)' | bc -l factorial
51090942171709440000

(2) PYTHON

The next instructions present easy methods to increase two to an arbitrary energy utilizing the Python programming language on the bash immediate. Observe using the backtick myvar=`command` syntax to assign the outcomes of the arithmetic to a bash variable. Python is broadly used and continuously already put in on Unix and Unix-like methods.

Observe that there must be no area between the variable title and the equal signal within the variable task.


bash$ python -c 'print 2**128'
340282366920938463463374607431768211456

bash$ MYVAR=`python -c 'print 2**128'`

bash$ echo $MYVAR
340282366920938463463374607431768211456

That is easy methods to compute an enormous factorial in Python (utilizing the Python math bundle):


bash$ python -c 'import math; print math.factorial(21);'
51090942171709440000

Python could be run interactively as follows:


bash$ python -i
Python 2.7.10 |Anaconda 2.1.0 (x86_64)| (default, Could 28 2015, 17:04:42) 
[GCC 4.2.1 (Apple Inc. build 5577)] on darwin
Sort "assist", "copyright", "credit" or "license" for extra data.
Anaconda is dropped at you by Continuum Analytics.
Please try: https://continuum.io/thanks and https://binstar.org
>>> 2**128
340282366920938463463374607431768211456L


(3) RUBY

The next instructions present easy methods to increase two (2) to an arbitrary energy utilizing the Ruby programming language on the bash immediate. Observe using the backtick myvar=`command` syntax to assign the outcomes of the arithmetic to a bash variable. Ruby is broadly used and typically already put in on Unix and Unix-like methods.

Observe that there must be no area between the variable title and the equal signal within the variable task.



bash$ ruby -e 'print 2**128, "n" '
340282366920938463463374607431768211456

bash$ MYVAR=`ruby -e 'print 2**128, "n" '`

bash$ echo $MYVAR
340282366920938463463374607431768211456


Ruby could be run interactively utilizing the irb command:


bash$ irb
irb(fundamental):001:0> print 2**128
340282366920938463463374607431768211456=> nil
irb(fundamental):002:0> 

RUBY doesn’t have a built-in factorial operate however you may outline one:

factorial.rb


def factorial(n)
        if n<= 1
            1
        else
            n * factorial( n - 1 )
        finish
finish

The file factorial.rb with the definition of factorial could be pre-loaded into the interactive ruby as follows (notice the “./” is IMPORTANT — DO NOT OMIT):


bash$ irb -r ./factorial.rb
irb(fundamental):001:0> factorial(5)
=> 120
irb(fundamental):002:0> factorial(21)
=> 51090942171709440000

This may be accomplished non-interactively on the bash command immediate:


bash$ echo 'factorial(21)' | irb -r ./factorial.rb
Swap to examine mode.
factorial(21)
51090942171709440000

or with:


bash$ echo 'print factorial(21), "n"' | ruby -r ./factorial.rb
51090942171709440000

or with:


bash$ ruby -r ./factorial.rb -e 'print factorial(21), "n"'
51090942171709440000

Conclusion

There are no less than 3 ways to carry out arbitrary precision integer arithmetic below the Unix or GNU Bourne Once more Shell (bash), both on the command immediate or in shell scripts. These are the bc arbitrary precision calculator language, the python programming language, and the ruby programming language.

BC is the most definitely to be pre-installed on a Unix system. BC performs each arbitrary precision integer and floating level arithmetic. Python is now pretty frequent. RUBY is changing into pretty frequent, however it’s nonetheless not as frequent as Python within the writer’s expertise.

© 2016 John F. McGowan

In regards to the Writer

John F. McGowan, Ph.D. solves issues utilizing arithmetic and mathematical software program, together with creating gesture recognition for contact gadgets, video compression and speech recognition applied sciences. He has in depth expertise creating software program in C, C++, MATLAB, Python, Visible Fundamental and plenty of different programming languages. He has been a Visiting Scholar at HP Labs creating pc imaginative and prescient algorithms and software program for cell gadgets. He has labored as a contractor at NASA Ames Analysis Middle concerned within the analysis and growth of picture and video processing algorithms and know-how. He has revealed articles on the origin and evolution of life, the exploration of Mars (anticipating the invention of methane on Mars), and low cost entry to area. He has a Ph.D. in physics from the College of Illinois at Urbana-Champaign and a B.S. in physics from the California Institute of Know-how (Caltech). He could be reached at [email protected].