For Ex : if I have an input variable x whose value is selected via logic
ar= {1,2,-3,4,-6,8};
x = 5
then the output should be 4
For Ex : if I have an input variable x whose value is selected via logic
ar= {1,2,-3,4,-6,8};
x = 5
then the output should be 4
In reply to uvm_va_1:
A.min() with (item<x? x-item: item-x)
Note that this returns an array with one element, or an empty array when A is empty.
In reply to dave_59:
Yes, I did for positive values, it works, I used a foreach loop and used this condition in that, it’s picking the correct value for positive numbers but for negative numbers it’s not quite working
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
In reply to DamianS:
I believe you may have run into a tool bug. I don’t think rounding errors would be an issue here. Three out of four simulators on EDAplayground produce the correct results.
This Mentor/Siemens EDA sponsored public forum is not for discussing tool specific usage or issues. Please read your tool’s user manual or contact your tool vendor directly for support.