Livt packages
Livt.Math
Version 1.7.2
Reusable integer and fixed-point arithmetic, complex numbers, trigonometry, and statistics for FPGA applications written in Livt.
Published files (90)
src/fixedpoint/Q15.lvt
namespace Livt.Math.FixedPoint
/**
* Signed Q1.15 fixed-point helper for normalized DSP coefficients.
* Instance operations clamp to [-32768, 32767] and store the latest value for GetResult().
* Static helpers return their value without modifying an instance.
*/
component Q15
{
// Compile-time dimensions, bounds, and numeric constants.
public const MIN: int = -32768
public const MAX: int = 32767
public const ZERO: int = 0
public const ONE: int = 32767
public const HALF: int = 16384
// Latest computed result, retained for the caller.
result: int
/**
* Initializes the stored result to zero; static helpers do not use this state.
*/
new()
{
result = 0
}
/**
* Returns value saturated to -32768..32767, without changing any instance result.
*/
public static fn ClampValue[](value: int) int
{
if (value < Q15.MIN) {
return Q15.MIN
}
if (value > 32767) {
return 32767
}
return value
}
/**
* Returns the saturated sum of two raw Q15 values in -32768..32767. Inputs must fit that
* range; does not change instance state.
*/
public static fn AddSaturatingValue[](a: int, b: int) int
{
var sum: int = a + b
return Q15.ClampValue(sum)
}
/**
* Returns the saturated difference of two raw Q15 values in -32768..32767. Inputs must fit
* that range; does not change instance state.
*/
public static fn SubSaturatingValue[](a: int, b: int) int
{
var difference: int = a - b
return Q15.ClampValue(difference)
}
/**
* Multiplies two raw Q15 values in -32768..32767, divides the integer product by 32768,
* and saturates the result. Does not change instance state.
*/
public static fn MulValue[](a: int, b: int) int
{
var product: int = a * b
var scaled: int = product / 32768
return Q15.ClampValue(scaled)
}
/**
* Clamp value into Q15 range and store it as the latest result.
*/
public fn Clamp(value: int)
{
if (value < -32768) {
result = -32768
} elif (value > 32767) {
result = 32767
} else {
result = value
}
}
/**
* Add two Q15-scaled values, saturate, and store the latest result.
*/
public fn AddSaturating(a: int, b: int)
{
var sum: int = a + b
this.Clamp(sum)
}
/**
* Subtract two Q15-scaled values, saturate, and store the latest result.
*/
public fn SubSaturating(a: int, b: int)
{
var difference: int = a - b
this.Clamp(difference)
}
/**
* Multiply two Q15-scaled values, rescale by 32768, saturate, and store the result.
*/
public fn Mul(a: int, b: int)
{
var product: int = a * b
var scaled: int = product / 32768
this.Clamp(scaled)
}
/**
* Return the latest stored Q15 result.
*/
public fn GetResult() int
{
return result
}
}