Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What would be an efficient way to select float in a finite sized array that is more close to zero?

For each function, I get/have a finite sized array of floats that I need to pick.

So if I have something like

1)

 {-0.02, 0.5, 0.98, -0.15, etc... }

I would pick "-0.02" from this list.

2)

 {-0.78, 0.003, 0.1, -1.8, etc... }

and now, I would pick "0.003" from this list.

This is just an example. In my real program, I have floats with 5-6 decimal points.

like image 632
jbchichoko Avatar asked Feb 19 '23 05:02

jbchichoko


1 Answers

std::min_element has an overload that takes a comparison function object; that's what I'd use here:

float val = *std::min_element(std::begin(v), std::end(v),
    [](float a, float b) { return fabs(a) < fabs(b); } );
like image 164
Jerry Coffin Avatar answered Apr 29 '23 21:04

Jerry Coffin