Skip to content

Instantly share code, notes, and snippets.

@dmitriykovalev
Created November 1, 2024 06:02
Show Gist options
  • Select an option

  • Save dmitriykovalev/633c3f9023a4ef5b7aedc820c8dd6387 to your computer and use it in GitHub Desktop.

Select an option

Save dmitriykovalev/633c3f9023a4ef5b7aedc820c8dd6387 to your computer and use it in GitHub Desktop.

Decibel

bits 2 ^ bits dB (power) dB (amplitude)
1 2 3.01 6.02
2 4 6.02 12.04
3 8 9.03 18.06
4 16 12.04 24.08
5 32 15.05 30.10
6 64 18.06 36.12
7 128 21.07 42.14
8 256 24.08 48.16
9 512 27.09 54.19
10 1024 30.10 60.21
11 2048 33.11 66.23
12 4096 36.12 72.25
13 8192 39.13 78.27
14 16384 42.14 84.29
15 32768 45.15 90.31
16 65536 48.16 96.33
17 131072 51.18 102.35
18 262144 54.19 108.37
19 524288 57.20 114.39
20 1048576 60.21 120.41
21 2097152 63.22 126.43
22 4194304 66.23 132.45
23 8388608 69.24 138.47
24 16777216 72.25 144.49
25 33554432 75.26 150.51
26 67108864 78.27 156.54
27 134217728 81.28 162.56
28 268435456 84.29 168.58
29 536870912 87.30 174.60
30 1073741824 90.31 180.62
31 2147483648 93.32 186.64
32 4294967296 96.33 192.66
dB ratio (power) ratio (amplitude)
0 1.00 1.00
1 1.26 1.12
2 1.58 1.26
3 2.00 1.41
4 2.51 1.58
5 3.16 1.78
6 3.98 2.00
7 5.01 2.24
8 6.31 2.51
9 7.94 2.82
10 10.00 3.16
11 12.59 3.55
12 15.85 3.98
13 19.95 4.47
14 25.12 5.01
15 31.62 5.62
16 39.81 6.31
17 50.12 7.08
18 63.10 7.94
19 79.43 8.91
20 100.00 10.00
21 125.89 11.22
22 158.49 12.59
23 199.53 14.13
24 251.19 15.85
25 316.23 17.78
26 398.11 19.95
27 501.19 22.39
28 630.96 25.12
29 794.33 28.18
30 1000.00 31.62
#!/usr/bin/env python3
#
# https://en.wikipedia.org/wiki/Decibel
#
# 1 B (bel) = 10 dB (decibel) = 10:1
#   B = log_10(a/b)
#
# Power:
#   dB  = 10*log_10(a/b), e.g. 3 dB = 10 * log_10(2:1)
#   a/b = 10^(dB/10)
#
# Amplitude:
#   dB  = 10*log_10((a/b)^2) = 20*log_10(a/b), e.g. 6 dB = 20 * log_10(2:1)
#   a/b = 10^(dB/20)
import math

def db_power(ratio):
  return 10 * math.log10(ratio)

def db_amplitude(ratio):
  return 20 * math.log10(ratio)

def print_power_of_two_to_db():
  print(f'| bits | 2 ^ bits   | dB (power) | dB (amplitude) |')
  print(f'|------|------------|------------|----------------|')
  for n in range(1, 33):
    m = 2**n
    dbp = db_power(m)
    dba = db_amplitude(m)
    print(f'| {n:4} | {m:<10} | {dbp:<10.2f} | {dba:<14.2f} |')

def power_ratio(db):
  return 10**(db / 10)

def amplitude_ratio(db):
  return 10**(db / 20)

def print_db_to_ratio():
  print(f'| dB  | ratio (power) | ratio (amplitude) |')
  print(f'|-----|---------------|-------------------|')
  for db in range(0, 31):
    pr = power_ratio(abs(db))
    ar = amplitude_ratio(abs(db))
    if db < 0:
      print(f'| {db:3} | 1/{pr:<11.2f} | 1/{ar:<15.2f} |')
    else:
      print(f'| {db:3} |   {pr:<11.2f} |   {ar:<15.2f} |')

print_power_of_two_to_db()
print()
print_db_to_ratio()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment