Skip to content

Conversation

roderickvd
Copy link
Member

This PR replaces truncating casts with proper rounding in float-to-integer sample conversions to eliminate systematic bias and nonlinear distortion.

Problem

The current implementation uses truncating casts (e.g. as i16), which creates two issues:

  1. Nonlinear distortion: All signal values in the interval (-1.0, 1.0) map to zero, creating an output bin twice as large as any other integer value. This violates the uniform quantization assumption and introduces harmonic distortion.

  2. Systematic bias towards zero: Small signals that should map to ±1 are instead lost to zero, introducing DC bias and reducing effective dynamic range by about 8 dB.

One publication that documents this is Dannenberg's "Danger in Floating-Point-to-Integer Conversion" letter to Computer Music Journal in 2002, which warns against truncation in audio applications.

Solution

Replace (s * scale) as {integer} with (s * scale).round() as {integer} for float-to-integer conversions.

Before (truncation):

s to_i16 { (s * 32_768.0) as i16 }  
// 0.1 * 32768 = 3276.8 → 3276 (truncated)
// 0.00002 * 32768 = 0.65536 → 0 (small signal lost)

After (rounding):

s to_i16 { (s * 32_768.0).round() as i16 }  
// 0.1 * 32768 = 3276.8 → 3277 (rounded)
// 0.00002 * 32768 = 0.65536 → 1 (small signal preserved)

The performance impact is minimal, because LLVM generates efficient code for round() intrinsics with dedicated instructions on most targets.

@roderickvd
Copy link
Member Author

roderickvd commented Sep 6, 2025

The failing build is unrelated and already present on master since cd8d893.

➡️ PR #192

@roderickvd roderickvd force-pushed the fix/round-float-to-int branch from 456ac1c to 0d048b3 Compare September 7, 2025 11:36
Replace truncating casts with proper rounding in float-to-integer sample
conversions to eliminate bias and preserve small signals.

Changes:
- Use f32::round() and f64::round() instead of truncating `as` casts
- Eliminates bias towards zero from truncation behavior
- Preserves small audio signals that would otherwise be truncated to zero
- Removes nonlinear distortion caused by signal values in (-1.0, 1.0)
  all mapping to zero, creating an interval twice as large as any other

Inlines sqrt and round functions for performance.

Additional tests verify proper rounding behavior for cases that would
fail with truncation.
@roderickvd roderickvd force-pushed the fix/round-float-to-int branch from 0d048b3 to 78bf2c3 Compare September 9, 2025 06:13
@roderickvd
Copy link
Member Author

Rebased and passing the CI now.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant