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/sqrt/SqrtInt32.lvt
namespace Livt.Math.Sqrt
/**
* Computes floor square roots for non-negative signed-int32 values.
*
* A restoring square-root implementation avoids multipliers and variable
* division. One pair of input bits is consumed per iteration, so the fixed
* 16 iterations cover every non-negative signed-int32 value exactly.
*/
component SqrtInt32
{
// Compile-time dimensions, bounds, and numeric constants.
public const ITERATIONS: int = 16
/**
* Returns floor(sqrt(value)); non-positive inputs return zero.
*/
public fn Compute(value: int) int
{
if (value <= 0) {
return 0
}
var radicand = value
var remainder = 0
var root = 0
for (var iteration = 0; iteration < ITERATIONS; iteration++) {
remainder = (remainder << 2) | ((radicand >> 30) & 3)
radicand = radicand << 2
root = root << 1
var candidate = (root << 1) + 1
if (remainder >= candidate) {
remainder -= candidate
root++
}
}
return root
}
}