Reputation: 19
I have a code that is increasing the value of a variable 'x' by 0.01 and do some calculations until it matches the value of another variable 'y'. While "X" is increasing, "y" is decreasing not linearly.
What would the best logic to find the value where 'x' and 'y' are the same or the closest? Increasing 'x' by 0.01 is doing the job, but as I'm really noob, I guess there is a clever way.
Thanks in advance
Upvotes: 0
Views: 78
Reputation: 17945
If I understand correctly, you want to find an x
such that f(x) = y
for a constant y
, and f(x)
is non-linear but has no other inputs. Is this correct?
Let us further assume that f(x)
is strictly increasing or decreasing (that is: it does not wiggle up and down and cross y
at several x
s). Then, you can use a standard binary search to find the single intercept:
find values
x_lo
such that f(x_lo) < y
x_hi
such that f(x_hi) > y
look at the midpoint m = (x_hi + x_lo) / 2
.
f(m) < y
, use x_lo = m
, and repeat this stepf(m) > y
, use x_hi = m
, and repeat this stepf(m) == y
, or it is close enough for your needs, you have finished!A simple way to find initial values for x_hi
and x_lo
that is to test f(any)
value, and assign x_hi=any
or x_lo=any
depending on whether it is larger or
smaller than y
. Once you have one extreme, you can quickly find the other by quickly increasing or decreasing it. Say we have x_lo
, we can test with x_hi = x_lo*(2^i)
for i=1, 2, 3, ...
, with ^
representing exponentiation.
If f(x)
crosses y
at several points, this does not work - because it can skip right over the important x
in step 2.
Upvotes: 1