Skip to content

Instantly share code, notes, and snippets.

@Moonbase59
Last active May 14, 2024 18:05
Show Gist options
  • Save Moonbase59/44bd2cb54865821044ba1fa22efb0d91 to your computer and use it in GitHub Desktop.
Save Moonbase59/44bd2cb54865821044ba1fa22efb0d91 to your computer and use it in GitHub Desktop.
Quickly calculate dB of amplitude, amplitude of dB on the command line, using bc
#!/bin/bash
# Save as "dboflin", create symlink as "linofdb"
# Calculate dB from amplitude, amplitude from dB, using bc.
# 2024-05-12 - Moonbase59
# 2024-05-14 - Moonbase59 - add correct rounding
#
# Note: For AMPLITUDE, the factor is 20,
# for POWER/ENERGY, the factor is 10!
fun=$(basename $0) # dboflin or linofdb
val=$1
if [ -z "$1" ] ; then
>&2 cat <<EOF
Usage:
$fun [value]
EOF
exit 1
fi
result=$(bc -l <<EOF
# Define functions for bc
# bc -l sets scale to 20
define pow(a, b) {
if (scale(b) == 0) {
return a ^ b;
}
return e(b*l(a));
}
# round x to d decimals
define r(x, d) {
auto r, s;
if (x < 0) {
return -r(-x, d)
}
r = x + 0.5*10^-d
s = scale
scale = d
r = r/1
scale = s
return r
}
# dB of amplitude, rounded to 2 decimals
define dboflin(x) {
auto result;
result = 20 * l(x) / l(10);
return r(result, 2);
}
# amplitude of dB, rounded to 6 decimals
define linofdb(x) {
auto result;
result = pow(10, x/20);
return r(result, 6);
}
# call either dboflin or linofdb, depending on $0
$fun($val)
EOF
)
echo $result
@Moonbase59
Copy link
Author

dboflin / linofdb

Save above in as dboflin in some place like ~/bin, /usr/local/bin, etc. (should be in path), chmod +x dboflin, then create a symlink ln -s dboflin linofdb.

You can then quickly calculate dB values from a linear amplitude (0..1), or linear values from a dB value:

matthias@e6510: ~_042

Bash script, uses the Linux Basic Calculator bc.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment