Calculating the gain for adjusting sound level to X db I have a sound signal, and I would like to implement a simple realtime level control (for info, I am using Pure Data, but I'd like to know about the general case).

For this I thought of using the envelope amplitude (in dB) of the input Vin_db, calculated over a window of N samples ; use it to calculate the gain G to apply to the signal to get an output with amplitude Vout_db. (Disclaimer : I am very rusty with maths and decibels ...)

So I took the wikipedia formula for decibels :

V_db = 10 * log10(P / P0)

=> 

Vin_db = 10 * log10(Pin / P0)

Vout_db = 10 * log10(Pout / P0)

And this gave me :

Pout = Pin * 10^((Vout_db - Vin_db) / 10)

=> 

G = 10^((Vout_db - Vin_db) / 10)

However, this doesn't seem to work ... When I measure the output level it is not the expected Vout. Is there a fundamental flaw in my reasoning ? Or just a calculation error ?

EDIT

Thanks to Paul R I found the correct formula (I need a 20 instead of a 10):

G = 10^((Vout_db - Vin_db) / 20)
You don't need to convert the voltages to dB, just calculate the required gain (as a factor) and then convert this to dB if necessary, i.e.

G = Vout / Vin                 # required gain (factor)

G_dB = 20 * log10(G)           # required gain (dB)


where 

Vin = input voltage
Vout = output voltage


If you really want to work with dB throughout then you can do it like this (should give the same answer):

Vin_dB = 20 * log10(Vin)       # input voltage (dB)

Vout_dB = 20 * log10(Vout)     # output voltage (dB)

G_dB = Vout_dB - Vin_dB        # required gain (dB)

G = 10 ^ (G_dB / 20)           # required gain (factor)