How to find a closest entry in an array using system verilog

Thanks Dave,

That’s a nice one liner, it works for pos and neg integers.
Unfortunately it doesn’t work for reals. Are the array manipulation methods intended for integers only? I’ve found some work on reals and some don’t…


module test();

real r[]= {1.1,2.1,-3.1,4.1,-6.1,8.1};
int i[]= {1,2,-3,4,-6,8};

real closest_r[1];
int closest_i[1];

real v_r;
int v_i;

function real closest_to(real a[], real v);
  real distance[], min_d;
  int min_idx;
  distance = new[a.size()];
  foreach (a[i]) begin
    distance[i] = a[i] < v ? v - a[i] : a[i] - v;
  end
  min_d = distance[0];
  min_idx = 0;
  foreach( distance[i] ) begin
    if (distance[i] < min_d) begin
      min_d = distance[i];
      min_idx = i;
    end 
  end
  return a[min_idx];
endfunction
 
initial begin
  v_i = -5;
  v_r = -5.5;
  closest_i = i.min() with (item < v_i ? v_i - item : item - v_i);
  closest_r = r.min() with (item < v_r ? v_r - item : item - v_r);
  $display("int:", closest_i[0]);
  $display("real:", closest_r[0]);
  $display("real2:", closest_to(r, v_r));

  v_i = 5;
  v_r = 5.0;
  closest_i = i.min() with (item < v_i ? v_i - item : item - v_i);
  closest_r = r.min() with (item < v_r ? v_r - item : item - v_r);
  $display("int:", closest_i[0]);
  $display("real2:", closest_to(r, v_r));
end

endmodule

int: -6
real: 1.1
real2: -6.1
int: 4
real: 1.1
real2: 4.1