fix: use rounding for float-to-integer conversions #191
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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: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.
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):
After (rounding):
The performance impact is minimal, because LLVM generates efficient code for
round()
intrinsics with dedicated instructions on most targets.