Best algorithm for doing fixed-point euclidean difference?

Summary

The problem at hand is to find a fast algorithm for computing the fixed-point Euclidean distance in 3D space on a 32-bit RISC-V processor with fast multiply but no arbitrary divide. The current approach involves calculating the distance squared using 16.16 fixed-point math and then performing a square root operation.

Root Cause

The root cause of the issue is the lack of a fast and efficient square root algorithm for fixed-point numbers. The current approach uses a naive method that involves calculating the distance squared and then performing a square root operation using a 16.16 fixed-point square root function. The main causes of the problem are:

  • Lack of arbitrary divide instruction
  • Need for fast and efficient square root algorithm for fixed-point numbers
  • Current approach is not optimized for fixed-point math

Why This Happens in Real Systems

This problem occurs in real systems because:

  • Fixed-point math is commonly used in embedded systems where division is slow or not available
  • Euclidean distance calculations are frequently used in computer graphics, game development, and scientific simulations
  • Optimized algorithms for fixed-point math are not always available or well-known

Real-World Impact

The real-world impact of this problem is:

  • Slow performance in applications that require fast Euclidean distance calculations
  • Inaccurate results due to approximations or rounding errors in fixed-point math
  • Increased power consumption due to inefficient algorithms

Example or Code

int32_t distance_Squared = (int32_t)((dx * (uint64_t)dx)>>16) + (int32_t)((dy * (uint64_t)dy)>>16) + (int32_t)((dz * (uint64_t)dz)>>16);
int32_t SBFSqrt( int32_t i ) {
    int sign = i < 0;
    if( sign ) i = -i;
    if( i == 0 ) return 0;
    int bclz = 31-__builtin_clz(i);
    int x = 1 <> 1));
    x += x>>1;
    // Do various tricks found here: https://en.wikipedia.org/wiki/Square_root_algorithms
    if( sign ) x = -x;
    return x;
}

How Senior Engineers Fix It

Senior engineers fix this problem by:

  • Using optimized algorithms for fixed-point math, such as the Babylonian method for square root calculation
  • Leveraging the properties of fixed-point numbers to reduce calculations and improve accuracy
  • Implementing fast and efficient square root algorithms using bit manipulation and shift operations

Why Juniors Miss It

Juniors may miss this solution because:

  • Lack of experience with fixed-point math and optimized algorithms
  • Unfamiliarity with bit manipulation and shift operations
  • Insufficient knowledge of numerical analysis and mathematical tricks for fast and efficient calculations