Welcome, guest | Sign In | My Account | Store | Cart

This is a simple way of expressing non-linear scales (such as decibels) in python. In stead of: gain = 10 ** (12/10.)

Use gain = 12 * dB

Python, 31 lines
 ``` 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31``` ```class DB: ''' Convience class for decibel scale. Other non-linear scales such as the richter scale could be handled similarly. Usage: dB = DB() . . (later) . gain = 15 * dB ''' def __rmul__(self, val): ''' Only allow multiplication from the right to avoid confusing situation like: 15 * dB * 10 ''' return 10 ** (val / 10.) def __test__(): dB = DB() gain = 10 * dB assert abs(gain - 10) < 1e-8 try: gain2 = dB * 10 raise Exception('Should raise a type error!') except TypeError: pass __test__() ```

Often it is convenient to define constants that convert non-standard units to the canonical set of units you have chosen for your program. For instance if your prefer angles to be specified in radians you might define two constants:

RAD = 1. DEG = 180./pi

Later, you may specify values in either unit as:

theta = 25 * DEG phi = pi/2 * RAD

This trick does not work however for non-linear scales such as decibels, AKA dBs. This simple recipe allows similar convenience for those such situations.

 Created by Justin Shaw on Tue, 2 Jan 2007 (PSF)

### Required Modules

• (none specified)