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/Q7.lvt

namespace Livt.Math.FixedPoint

/**
 * Signed Q1.7 fixed-point helper for compact normalized coefficients.
 * Instance operations clamp to [-128, 127] and store the latest value for GetResult().
 * Static helpers return their value without modifying an instance.
 */
component Q7
{
	// Compile-time dimensions, bounds, and numeric constants.
	public const MIN: int = -128
	public const MAX: int = 127
	public const ZERO: int = 0
	public const ONE: int = 127
	public const HALF: int = 64

	// 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 -128..127, without changing any instance result.
	 */
	public static fn ClampValue[](value: int) int
	{
		if (value < Q7.MIN) {
			return Q7.MIN
		}

		if (value > 127) {
			return 127
		}

		return value
	}

	/**
	 * Returns the saturated sum of two raw Q7 values in -128..127. 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 Q7.ClampValue(sum)
	}

	/**
	 * Returns the saturated difference of two raw Q7 values in -128..127. 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 Q7.ClampValue(difference)
	}

	/**
	 * Multiplies two raw Q7 values in -128..127, divides the integer product by 128, 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 / 128
		return Q7.ClampValue(scaled)
	}

	/**
	 * Clamp value into Q7 range and store it as the latest result.
	 */
	public fn Clamp(value: int)
	{
		if (value < -128) {
			result = -128
		} elif (value > 127) {
			result = 127
		} else {
			result = value
		}
	}

	/**
	 * Add two Q7-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 Q7-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 Q7-scaled values, rescale by 128, saturate, and store the result.
	 */
	public fn Mul(a: int, b: int)
	{
		var product: int = a * b
		var scaled: int = product / 128
		this.Clamp(scaled)
	}

	/**
	 * Return the latest stored Q7 result.
	 */
	public fn GetResult() int
	{
		return result
	}
}