Bash Script to Calculate Compound Interest Easily
amount = principal * (1 + rate/100/n)^(n*time) using bc -l for floating-point math, for example: amount=$(echo "$principal * (1 + $rate / 100 / $n) ^ ($n * $time)" | bc -l).Examples
How to Think About It
Algorithm
Code
#!/bin/bash read -p "Enter principal amount: " principal read -p "Enter annual interest rate (in %): " rate read -p "Enter time in years: " time read -p "Enter number of times interest compounded per year: " n amount=$(echo "$principal * (1 + $rate / 100 / $n) ^ ($n * $time)" | bc -l) printf "Compound Interest Amount: %.2f\n" "$amount"
Dry Run
Let's trace the example with principal=1000, rate=5, time=2, n=1 through the code
Input values
principal=1000, rate=5, time=2, n=1
Calculate compound factor
1 + 5 / 100 / 1 = 1.05
Calculate power
1.05 ^ (1 * 2) = 1.1025
Calculate amount
1000 * 1.1025 = 1102.5
| Step | Calculation | Result |
|---|---|---|
| 1 | 1 + 5/100/1 | 1.05 |
| 2 | 1.05 ^ 2 | 1.1025 |
| 3 | 1000 * 1.1025 | 1102.5 |
Why This Works
Step 1: Use of formula
The formula amount = principal * (1 + rate/100/n)^(n*time) calculates how money grows with compound interest.
Step 2: Floating-point math
Bash cannot do decimal math natively, so bc -l is used to handle floating-point calculations.
Step 3: Rounding output
The printf command formats the output to two decimal places for currency style.
Alternative Approaches
read -p "Principal: " p; read -p "Rate: " r; read -p "Time: " t; read -p "Compounds per year: " n; awk -v p=$p -v r=$r -v t=$t -v n=$n 'BEGIN {amount=p*(1+r/100/n)^(n*t); printf "Compound Interest Amount: %.2f\n", amount}'
read -p "Principal: " p; read -p "Rate: " r; read -p "Time: " t; read -p "Compounds per year: " n; amount=$(echo "scale=4; $p * (1 + $r / 100 / $n) ^ ($n * $t)" | bc -l); printf "Compound Interest Amount: %.2f\n" "$amount"
Complexity: O(1) time, O(1) space
Time Complexity
The calculation involves a fixed number of arithmetic operations and a power function call, so it runs in constant time.
Space Complexity
Only a few variables are stored, so space usage is constant.
Which Approach is Fastest?
Using awk or bc both run quickly for this simple calculation; differences are negligible for single calculations.
| Approach | Time | Space | Best For |
|---|---|---|---|
| bc -l | O(1) | O(1) | Precision and portability |
| awk | O(1) | O(1) | Simpler syntax, no external calls |
| bc with scale | O(1) | O(1) | Control decimal precision explicitly |
bc -l or awk for decimal math in Bash scripts.bc or awk causes incorrect results.