Skip to main content
The math module provides comprehensive mathematical operations for bash scripts, from basic integer arithmetic to advanced floating-point calculations, trigonometry, and unit conversions.

Constants

The module provides high-precision mathematical constants (42 digits):
MATH_PI="3.141592653589793238462643383279502884197169"
MATH_E="2.718281828459045235360287471352662497757237"
MATH_PHI="1.618033988749894848204586834365638117720309"
MATH_SQRT2="1.414213562373095048801688724209698078569671"
MATH_SQRT3="1.732050808568877293527446341505872366942805"
MATH_LN2="0.693147180559945309417232121458176568075500"
MATH_LN10="2.302585092994045684017991454684364207601101"
MATH_TAU="6.283185307179586476925286766559005768394338"  # 2π
MATH_EULER_MASCHERONI="0.577215664901532860606512090082402431042159"  # γ
MATH_CATALAN="0.915965594177219015054603514932384110774149"
MATH_APERY="1.202056903159594285399738161511449990764986"  # ζ(3)

Configuration

MATH_SCALE - Sets decimal precision for floating-point operations (default: 10)
MATH_SCALE=20  # Use 20 decimal places

BC wrapper

math::has_bc()

Check if bc is available for floating-point operations. Returns: 0 if available, 1 otherwise
if math::has_bc; then
    echo "BC is available"
fi

math::bc(expr, [scale])

Execute a bc expression with specified precision. Parameters:
  • expr - BC expression to evaluate
  • scale - Decimal places (optional, defaults to MATH_SCALE)
Returns: Calculated result
math::bc "4 * a(1)" 42  # Calculate π with 42 decimal places

Basic integer arithmetic

Pure bash implementations requiring no external dependencies.
Calculate absolute value of an integer.Parameters:
  • n - Integer value
Returns: Absolute value
math::abs -42  # Returns: 42
math::abs 15   # Returns: 15
Implementation:
echo $(( $1 < 0 ? -$1 : $1 ))
Return the minimum of two values.Parameters:
  • a - First value
  • b - Second value
Returns: Smaller value
math::min 10 20  # Returns: 10
Return the maximum of two values.Parameters:
  • a - First value
  • b - Second value
Returns: Larger value
math::max 10 20  # Returns: 20
Constrain a value between minimum and maximum (inclusive).Parameters:
  • n - Value to clamp
  • min - Minimum bound
  • max - Maximum bound
Returns: Clamped value
math::clamp 15 10 20   # Returns: 15
math::clamp 5 10 20    # Returns: 10
math::clamp 25 10 20   # Returns: 20
Implementation:
echo $(( n < lo ? lo : (n > hi ? hi : n) ))
Floating-point version of clamp (requires bc).Parameters:
  • n - Value to clamp
  • min - Minimum bound
  • max - Maximum bound
  • scale - Decimal places (optional)
Returns: Clamped floating-point value
math::clampf 3.7 0 1 2  # Returns: 1.00
Integer division (truncated toward zero).Parameters:
  • dividend - Number to divide
  • divisor - Number to divide by
Returns: Integer quotient
math::div 10 3  # Returns: 3
Modulo operation.Parameters:
  • dividend - Number to divide
  • divisor - Modulus
Returns: Remainder
math::mod 10 3  # Returns: 1
Integer exponentiation using fast exponentiation algorithm.Parameters:
  • base - Base number
  • exponent - Power to raise to
Returns: base^exponent
math::pow 2 10  # Returns: 1024
Sum a sequence of integers.Parameters:
  • Variable number of integers
Returns: Sum of all arguments
math::sum 1 2 3 4 5  # Returns: 15
Calculate product of a sequence of integers.Parameters:
  • Variable number of integers
Returns: Product of all arguments
math::product 2 3 4  # Returns: 24

Floating-point operations

Requires bc for calculations. All functions support optional scale parameter.
Return largest integer ≤ n.Parameters:
  • n - Number to floor
Returns: Floor value
math::floor 3.7   # Returns: 3
math::floor -2.3  # Returns: -3
Return smallest integer ≥ n.Parameters:
  • n - Number to ceiling
Returns: Ceiling value
math::ceil 3.2   # Returns: 4
math::ceil -2.8  # Returns: -2
Round to nearest integer or specified decimal places.Parameters:
  • n - Number to round
  • decimal_places - Precision (optional, default 0)
Returns: Rounded value
math::round 3.7      # Returns: 4
math::round 3.14159 2  # Returns: 3.14
Calculate square root.Parameters:
  • n - Number
  • scale - Decimal places (optional)
Returns: √n
math::sqrt 2 10  # Returns: 1.4142135623
Natural logarithm (base e).Parameters:
  • n - Number
Returns: ln(n)
math::log 2.718281828  # Returns: ~1
Logarithm base 2.Parameters:
  • n - Number
Returns: log₂(n)
math::log2 1024  # Returns: 10
Logarithm base 10.Parameters:
  • n - Number
Returns: log₁₀(n)
math::log10 1000  # Returns: 3
Logarithm with arbitrary base.Parameters:
  • value - Number
  • base - Logarithm base
Returns: log_base(value)
math::logn 81 3  # Returns: 4
Exponential function e^n.Parameters:
  • n - Exponent
Returns: e^n
math::exp 1  # Returns: 2.718281828...
Floating-point power function.Parameters:
  • base - Base number
  • exponent - Power (can be fractional)
Returns: base^exponent
math::powf 2 0.5  # Returns: 1.4142135623 (√2)

Trigonometry

All angles in radians unless noted. Requires bc.
Sine function.
math::sin "$MATH_PI/2"  # Returns: 1
Cosine function.
math::cos "$MATH_PI"  # Returns: -1
Tangent function.
math::tan "$MATH_PI/4"  # Returns: 1
Arcsine (inverse sine).Parameters:
  • value - Value in range [-1, 1]
Returns: Angle in radians
math::asin 0.5  # Returns: π/6
Arccosine (inverse cosine).Parameters:
  • value - Value in range [-1, 1]
Returns: Angle in radians
Arctangent (inverse tangent).Parameters:
  • value - Any number
Returns: Angle in radians
math::atan 1  # Returns: π/4
Two-argument arctangent.Parameters:
  • y - Y coordinate
  • x - X coordinate
Returns: Angle in radians
Convert degrees to radians.
math::deg_to_rad 180  # Returns: π
math::deg_to_rad 90   # Returns: π/2
Convert radians to degrees.
math::rad_to_deg "$MATH_PI"  # Returns: 180

Percentage and ratio functions

Calculate percentage: (part / total) × 100.Parameters:
  • part - Partial value
  • total - Total value
  • scale - Decimal places (optional, default 2)
Returns: Percentage
math::percent 25 100      # Returns: 25.00
math::percent 1 3 4       # Returns: 33.3333
Calculate what value is p% of total.Parameters:
  • percent - Percentage
  • total - Total value
  • scale - Decimal places (optional)
Returns: Value
math::percent_of 20 500  # Returns: 100.00
Calculate percentage change from old to new value.Parameters:
  • old - Original value
  • new - New value
  • scale - Decimal places (optional)
Returns: Percentage change
math::percent_change 100 150  # Returns: 50.00 (50% increase)
math::percent_change 200 150  # Returns: -25.00 (25% decrease)

Interpolation and mapping

Linear interpolation between a and b by factor t (0.0-1.0).Parameters:
  • a - Start value
  • b - End value
  • t - Interpolation factor (clamped to 0-1)
  • scale - Decimal places (optional)
Returns: Interpolated value
math::lerp 0 100 0.5    # Returns: 50
math::lerp 10 20 0.25   # Returns: 12.5
Linear interpolation without clamping t to [0,1].Parameters:
  • a - Start value
  • b - End value
  • t - Interpolation factor (not clamped)
  • scale - Decimal places (optional)
Returns: Interpolated value
math::lerp_unclamped 0 10 2  # Returns: 20 (extrapolation)
Map a value from one range to another.Parameters:
  • value - Input value
  • in_min - Input range minimum
  • in_max - Input range maximum
  • out_min - Output range minimum
  • out_max - Output range maximum
  • scale - Decimal places (optional)
Returns: Mapped value
math::map 5 0 10 0 100    # Returns: 50
math::map 2.5 0 5 0 1 2   # Returns: 0.50
Normalize a value to 0.0-1.0 range.Parameters:
  • value - Input value
  • min - Range minimum
  • max - Range maximum
  • scale - Decimal places (optional)
Returns: Normalized value (0.0-1.0)
math::normalize 50 0 100  # Returns: 0.5
math::normalize 75 0 100  # Returns: 0.75

Number theory and combinatorics

Greatest common divisor (Euclidean algorithm).Parameters:
  • a - First integer
  • b - Second integer
Returns: GCD
math::gcd 48 18  # Returns: 6
Least common multiple.Parameters:
  • a - First integer
  • b - Second integer
Returns: LCM
math::lcm 12 18  # Returns: 36
Check if integer is even.Returns: 0 if even, 1 if odd
math::is_even 4 && echo "Even"  # Prints: Even
Check if integer is odd.Returns: 0 if odd, 1 if even
math::is_odd 5 && echo "Odd"  # Prints: Odd
Check if integer is prime.Parameters:
  • n - Integer to check
Returns: 0 if prime, 1 if composite
math::is_prime 17 && echo "Prime"  # Prints: Prime
math::is_prime 18 || echo "Not prime"  # Prints: Not prime
Calculate factorial n!.Parameters:
  • n - Non-negative integer
Returns: n!
math::factorial 5  # Returns: 120
math::factorial 0  # Returns: 1
Calculate nth Fibonacci number (0-indexed).Parameters:
  • n - Index (0-based)
Returns: Fibonacci number
math::fibonacci 0   # Returns: 0
math::fibonacci 1   # Returns: 1
math::fibonacci 10  # Returns: 55
Integer square root (floor).Parameters:
  • n - Non-negative integer
Returns: ⌊√n⌋
math::int_sqrt 50  # Returns: 7
math::int_sqrt 64  # Returns: 8
Binomial coefficient C(n,k) - “n choose k”.Parameters:
  • n - Total items
  • k - Items to choose
Returns: C(n,k)
math::choose 5 2  # Returns: 10
math::choose 10 3  # Returns: 120
Number of permutations P(n,k).Parameters:
  • n - Total items
  • k - Items to arrange
Returns: P(n,k)
math::permute 5 2  # Returns: 20
Sum of digits of an integer.Parameters:
  • n - Integer (sign ignored)
Returns: Sum of digits
math::digit_sum 12345  # Returns: 15
math::digit_sum -999   # Returns: 27
Count number of digits.Parameters:
  • n - Integer (sign ignored)
Returns: Number of digits
math::digit_count 12345  # Returns: 5
math::digit_count 0      # Returns: 1
Reverse digits of an integer.Parameters:
  • n - Integer
Returns: Reversed number (preserves sign)
math::digit_reverse 12345  # Returns: 54321
math::digit_reverse -789   # Returns: -987
Check if integer is a palindrome.Parameters:
  • n - Integer (sign ignored)
Returns: 0 if palindrome, 1 otherwise
math::is_palindrome 12321 && echo "Palindrome"  # Prints: Palindrome

Unit conversion

math::unitconvert(from, to, value, [scale])

Universal unit conversion dispatcher supporting temperature, length, mass, volume, speed, pressure, energy, power, digital storage, time, and angles. Parameters:
  • from - Source unit (case-insensitive)
  • to - Target unit (case-insensitive)
  • value - Value to convert
  • scale - Decimal places (optional)
Returns: Converted value

Supported conversions

Units: celsius (c), fahrenheit (f), kelvin (k)
math::unitconvert celsius fahrenheit 100    # Returns: 212
math::unitconvert fahrenheit celsius 32     # Returns: 0
math::unitconvert celsius kelvin 0          # Returns: 273.15
Units: fm, pm, nm, um, mm, cm, m, km, in, ft, yd, mi, nautical_mile (nm), au, ly, lh, ld, pc
math::unitconvert km mi 100                 # Kilometers to miles
math::unitconvert m ft 10                   # Meters to feet
math::unitconvert in cm 12                  # Inches to centimeters
math::unitconvert ly km 1                   # Light year to km
math::unitconvert au km 1                   # Astronomical unit to km
Units: ug, mg, g, kg, t (metric ton), oz, lb, st (stone)
math::unitconvert kg lb 100                 # Returns: 220.462
math::unitconvert lb kg 150                 # Pounds to kilograms
math::unitconvert g oz 100                  # Grams to ounces
Units: ml, l, m3, tsp, tbsp, floz, pt, qt, gal
math::unitconvert l gal 10                  # Liters to gallons
math::unitconvert ml floz 500               # Milliliters to fluid ounces
math::unitconvert gal l 5                   # Gallons to liters
Units: kmh (kph), mph, ms (m/s), knot, mach, c (speed of light)
math::unitconvert kmh mph 100               # km/h to mph
math::unitconvert ms kmh 30                 # m/s to km/h
math::unitconvert mach ms 1                 # Mach to m/s
Units: pa, kpa, bar, atm, psi, mmhg (torr)
math::unitconvert atm pa 1                  # Atmospheres to pascals
math::unitconvert psi pa 14.7               # PSI to pascals
Units: j, kj, cal, kcal, kwh, ev, btu
math::unitconvert j cal 1000                # Joules to calories
math::unitconvert kcal j 1                  # Kilocalories to joules
math::unitconvert kwh j 1                   # kWh to joules
Units: w, kw, hp (horsepower)
math::unitconvert kw hp 100                 # Kilowatts to horsepower
math::unitconvert hp w 5                    # Horsepower to watts
Units: b, kb, mb, gb, tb, pb (decimal), kib, mib, gib, tib, pib (binary), sector (512B), sector4k (4K)
math::unitconvert gb mb 5                   # Gigabytes to megabytes
math::unitconvert b gib 1073741824          # Bytes to gibibytes
math::unitconvert gib sector 100            # GiB to sectors
Units: fs, ps, ns, us, ms, s, min, h, d, week, year
math::unitconvert h min 2                   # Hours to minutes
math::unitconvert d h 7                     # Days to hours
math::unitconvert femtosecond nanosecond 1000
Units: deg, rad, grad (gon), arcmin, arcsec
math::unitconvert deg rad 180               # Returns: π
math::unitconvert rad deg 3.14159           # Returns: ~180
math::unitconvert deg arcmin 1              # Returns: 60

Usage examples

Calculate compound interest

#!/bin/bash
source math.sh

principal=1000
rate=5  # 5% annual
years=10

# A = P(1 + r/100)^t
factor=$(math::powf 1.05 $years)
amount=$(math::bc "$principal * $factor" 2)

echo "Investment grows to: \$$amount"

Distance calculator

# Calculate distance between two points
x1=3 y1=4
x2=6 y2=8

dx=$(math::abs $((x2 - x1)))
dy=$(math::abs $((y2 - y1)))
dist_sq=$((dx*dx + dy*dy))
dist=$(math::sqrt $dist_sq 2)

echo "Distance: $dist units"

Convert units in bulk

# Convert temperatures
for temp in 0 20 37 100; do
    f=$(math::unitconvert c f $temp 1)
    echo "${temp}°C = ${f}°F"
done

Build docs developers (and LLMs) love