oliddan
oliddan

Reputation: 19

What is the fastest way to increase the value of a variable until it matches the value of another variable in Javascript?

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

Answers (1)

tucuxi
tucuxi

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 xs). Then, you can use a standard binary search to find the single intercept:

  1. find values

    • x_lo such that f(x_lo) < y
    • x_hi such that f(x_hi) > y
  2. look at the midpoint m = (x_hi + x_lo) / 2.

    • if f(m) < y, use x_lo = m, and repeat this step
    • if f(m) > y, use x_hi = m, and repeat this step
    • if f(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

Related Questions