What would be an efficient way to select a float in an array of finite size that is closer to zero?

For each function, I get / have an array of arrays with a finite size that I need to select.

So, if I have something like

1)

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

I would choose "-0.02" from this list.

2)

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

and now I would select "0.003" from this list.

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

+4
source share
4 answers

std::min_element has an overload that takes an object of the comparison function; what i will use here:

 float val = *std::min_element(std::begin(v), std::end(v), [](float a, float b) { return fabs(a) < fabs(b); } ); 
+6
source

You have to go through all the numbers in the array, so the most efficient answer will be in O (n).

As soon as you know this, you realize that you simply look at each number and check if it is approaching zero, that the last one you have chosen makes a deal.

+1
source

Use std :: min_element with a comparison function that should archive what you want.

 template<class T> const T& abs_min(const T& a, const T& b) { return (fabs(a) < fabs(b)) ; } const SIZE = 5; float v[SIZE ] {-0.78, 0.003, 0.1, -1.8, 0.8}; float val = *std::min_element(v, v+SIZE , min_abs); 
+1
source
  • if you need to use an array and it is small in size - just repeat, for example std::min_element
  • if you have the freedom to choose the ordered container std::set<> . then use it=std::set::lower_bound(0) and compare *it with *(it+1) . it will scale better for large data sizes.
0
source

All Articles