1
0
Fork 0

Add a gain to decibel conversion function

This commit is contained in:
Robbert van der Helm 2022-01-26 11:57:47 +01:00
parent 5cd14492ea
commit 71a910fa75

View file

@ -16,7 +16,7 @@
pub const MINUS_INFINITY_DB: f32 = -100.0; pub const MINUS_INFINITY_DB: f32 = -100.0;
/// Convert decibels to gain, treating anything below -100 dB as minus infinity. /// Convert decibels to a voltage gain ratio, treating anything below -100 dB as minus infinity.
pub fn db_to_gain(dbs: f32) -> f32 { pub fn db_to_gain(dbs: f32) -> f32 {
if dbs > MINUS_INFINITY_DB { if dbs > MINUS_INFINITY_DB {
10.0f32.powf(dbs * 0.05) 10.0f32.powf(dbs * 0.05)
@ -25,6 +25,16 @@ pub fn db_to_gain(dbs: f32) -> f32 {
} }
} }
/// Convert a voltage gain ratio to decibels. Gain ratios that aren't positive will be treated as
/// [MINUS_INFINITY_DB].
pub fn gain_to_db(gain: f32) -> f32 {
if gain > 0.0 {
gain.log10() * 20.0
} else {
MINUS_INFINITY_DB
}
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
@ -43,4 +53,24 @@ mod tests {
fn test_db_to_gain_minus_infinity() { fn test_db_to_gain_minus_infinity() {
assert_eq!(db_to_gain(-100.0), 0.0); assert_eq!(db_to_gain(-100.0), 0.0);
} }
#[test]
fn test_gain_to_db_positive() {
assert_eq!(gain_to_db(4.0), 12.041201);
}
#[test]
fn test_gain_to_db_negative() {
assert_eq!(gain_to_db(0.25), -12.041201);
}
#[test]
fn test_gain_to_db_minus_infinity_zero() {
assert_eq!(gain_to_db(0.0), MINUS_INFINITY_DB);
}
#[test]
fn test_gain_to_db_minus_infinity_negative() {
assert_eq!(gain_to_db(-2.0), MINUS_INFINITY_DB);
}
} }