All Projects → clarity20 → shellmath

clarity20 / shellmath

Licence: other
Yes, Virginia, you can do floating-point arithmetic in Bash!

Programming Languages

shell
77523 projects

Projects that are alternatives of or similar to shellmath

verrou
floating-point errors checker
Stars: ✭ 39 (+18.18%)
Mutual labels:  arithmetic, floating-point
uniswapv3-calculator
An all-in-one platform for Uniswap liquidity providers (prev Uniswap Calculator)
Stars: ✭ 131 (+296.97%)
Mutual labels:  calculator
Turbo-Transpose
Transpose: SIMD Integer+Floating Point Compression Filter
Stars: ✭ 50 (+51.52%)
Mutual labels:  floating-point
herbie
Optimize floating-point expressions for accuracy
Stars: ✭ 614 (+1760.61%)
Mutual labels:  floating-point
DecFP.jl
Julia IEEE decimal floating-point via the Intel decimal-float library
Stars: ✭ 49 (+48.48%)
Mutual labels:  floating-point
asm-docs
Documentation about native assembly programming on the TI CE calculators (84+CE / 83PCE)
Stars: ✭ 41 (+24.24%)
Mutual labels:  calculator
WarpPI
WarpPI Calculator, Step-by-step algebra calculator for Raspberry Pi. (abandoned project)
Stars: ✭ 93 (+181.82%)
Mutual labels:  calculator
Love-Calculator
Let's Calculate love with real data. Love Calculator by Mohammed Cha
Stars: ✭ 54 (+63.64%)
Mutual labels:  calculator
spfpm
Package for performing fixed-point, arbitrary-precision arithmetic in Python.
Stars: ✭ 61 (+84.85%)
Mutual labels:  arithmetic
mathpad
Interactive scratchpad calculator for VS Code
Stars: ✭ 20 (-39.39%)
Mutual labels:  calculator
attribute-depends-calculator
Automatically calculate a collection of depends attribute of ActiveRecord
Stars: ✭ 41 (+24.24%)
Mutual labels:  calculator
Kelvin
A powerful language for symbolic computation written in Swift.
Stars: ✭ 23 (-30.3%)
Mutual labels:  calculator
availability-calculator
Calculate how much downtime should be permitted in your Service Level Agreement or Objective
Stars: ✭ 60 (+81.82%)
Mutual labels:  calculator
netcalc
Advanced network calculator and address planning helper
Stars: ✭ 20 (-39.39%)
Mutual labels:  calculator
Sm4sh-Calculator
Web based Smash 4 knockback calculator
Stars: ✭ 12 (-63.64%)
Mutual labels:  calculator
bc
some useful math functions for linux calculator bc
Stars: ✭ 18 (-45.45%)
Mutual labels:  calculator
FpDebug
Dynamic Program Analysis based on Valgrind to find Floating-Point Accuracy Problems
Stars: ✭ 19 (-42.42%)
Mutual labels:  floating-point
30secondchallenge
Inspired by the newspaper puzzle my wife's grandma tests me with each time I visit.
Stars: ✭ 19 (-42.42%)
Mutual labels:  arithmetic
react-calculator
📐 PWA React + Redux Calculator
Stars: ✭ 65 (+96.97%)
Mutual labels:  calculator
FixedPointsArduino
A fixed point arithmetic library for Arduino
Stars: ✭ 68 (+106.06%)
Mutual labels:  arithmetic

Shellmath

Introducing floating-point arithmetic libraries for the Bash shell, because they said it couldn't be done... and because:

.

image info

Quick-start guide

Download this project and source the file shellmath.sh into your shell script, then fire away at the shellmath API!

The basic API looks like this:

    _shellmath_add        arg1   arg2  [...]  argN
    _shellmath_subtract   arg1   arg2               # means arg1 - arg2
    _shellmath_multiply   arg1   arg2  [...]  argN
    _shellmath_divide     arg1   arg2               # means arg1 / arg2

The extended API introduces one more function:

    _shellmath_getReturnValue   arg

This function optimizes away the need for $( subshelling ) in order to capture shellmath's output. To use this feature, just be sure to set __shellmath_isOptimized=1 at the top of your script. (You can find an example in faster_e_demo.sh.)

Operands to the shellmath functions can be integers or decimal numbers presented in either standard or scientific notation:

    _shellmath_add   1.009   4.223e-2
    _shellmath_getReturnValue   sum
    echo "The sum is $sum"

Addition and multiplication are of arbitrary arity; try this on for size:

    _shellmath_multiply  1  2  3  4  5  6
    _shellmath_getReturnValue   sixFactorial
    echo "6 factorial is $sixFactorial"

Subtraction and division, OTOH, are exclusively binary operations.

The demos

For a gentle introduction to shellmath run the demo slower_e_demo.sh with a small whole-number argument, say 15:

$ slower_e_demo.sh 15
e = 2.7182818284589936

This script uses a few shellmath API calls to calculate e, the mathematical constant also known as Euler's number. The argument 15 tells the script to evaluate the 15th-degree Maclaurin polynomial for e. (That's the Taylor polynomial centered at 0.) Take a look inside the script to see how it uses the shellmath APIs.

There is another demo script very much like this one but different, and the sensitive user can feel the difference. Try the following, but don't blink or you'll miss it ;)

$ faster_e_demo.sh 15
e = 2.7182818284589936

Did you feel the difference? Try the -t option with both scripts; this will produce timing statistics. Here are my results when running from my minGW64 command prompt on Windows 10 with an Intel i3 Core CPU:

$ for n in {1..5}; do faster_e_demo.sh -t 15 2>&1; done | awk '/^real/ {print $2}'
0m0.055s
0m0.051s
0m0.056s
0m0.054s
0m0.054s

$ for n in {1..5}; do slower_e_demo.sh -t 15 2>&1; done | awk '/^real/ {print $2}'
0m0.498s
0m0.594s
0m0.536s
0m0.511s
0m0.580s

(When sizing up these timings, do keep in mind that we are timing the calculation of e from its Maclaurin polynomial. Every invocation of either script is exercising the shellmath arithmetic subroutines 31 times.)

The comment header in faster_e_demo.sh explains the optimization and shows how to put this faster version to work for you.

Runtime efficiency competitive with awk and bc

The file timingData.txt captures the results of some timing experiments that compare shellmath against the GNU versions of the calculators awk and bc. The experiments exercised each of the arithmetic operations and captured the results in a shell variable. The result summary below shows that shellmath is competitive with awk and runs faster than bc in these experiments. (One commenter noted that the differences in execution speed can be partially explained by the fact that shellmath and awk use finite precision whereas bc uses arbitrary precision. Another factor in these measurements is the need to subshell 'awk' and 'bc' to capture their results, whereas 'shellmath' writes directly to the shell's global memory.)

Here are the run times of shellmath as a percentage of the awk and bc equivalents:

                    versus awk    versus bc
   Addition:          82.2%         40.6%
   Subtraction:       95.9%         50.5%
   Multiplication:   135.9%         73.3%
   Division:          80.3%         43.2%

Astute observers will note the experiments provide approximations to the sum, difference, product, and quotient of pi and e. Unfortunately I did not gain insight as to which of these values, if any, are transcendental.

You can find a deeper discussion of shellmath's runtime efficiency here.

Background

The Bash shell does not have built-in operators for decimal arithmetic, making it something of an oddity among well-known, widely-used programming languages. For the most part, practitioners in need of powerful computational building blocks have naturally opted for other languages and tools. Their widespread availability has diverted attention from the possibility of implementing decimal arithmetic in Bash and it's easy to assume that this cannot be done:

Meanwhile,

But finally, a glimmer of hope:

  • A diamond-in-the-rough buried elsewhere on Stack Overflow.
    This down-and-dirty milestone computes the decimal quotient of two integer arguments. At a casual glance, it seems to have drawn inspiration from the Euclidean algorithm for computing GCDs, an entirely different approach than shellmath's.

Please try shellmath on for size and draw your own conclusions!

How it works

shellmath splits decimal numbers into their integer and fractional parts, performs the appropriate integer operations on the parts, and recombines the results. (In the spirit of Bash, numerical overflow is silently ignored.)

Because if we can get carrying, borrowing, place value, and the distributive law right, then the sky's the limit! As they say--erm, as they said in Rome,

    Ad astra per aspera.

And now...

You can run your floating-point calculations directly in Bash!

Please see also:

A short discussion on arbitrary precision and shellmath

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].