Question

I have two sorted arrays, one containing factors (array a) that when multiplied with values from another array (array b), yields the desired value:

a(idx1) * b(idx2) = value

With idx2 known, I would like find the idx1 of a that provides the factor necessary to get as close to value as possible.

I have looked at some different algorithms (like this one, for example), but I feel like they would all be subject to potential problems with floating point arithmetic in my particular case.

Could anyone suggest a method that would avoid this?

Was it helpful?

Solution

If I understand correctly, this expression

minloc(abs(a-value/b(idx2)))

will return the the index into a of the first occurrence of the value in a which minimises the difference. I expect that the compiler will write code to scan all the elements in a so this may not be faster in execution than a search which takes advantage of the knowledge that a and b are both sorted. In compensation, this is much quicker to write and, I expect, to debug.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top