mathequation-solvingfactoring

How to solve z = (((m / k) / j) / x) for x optimizing z towards 2ˣ


So say I have these variables:

Then we have

let z = (((m / k) / j) / x)

So for example, say we have this:

Then we have

let z = ((2000000 / 5) / 10) / x

I would like to figure out what x is given that z should be as close to 2 to the power of x as possible. The way I am currently doing this is by just plugging in numbers and trying to get them close to matching. But I'm wondering a generic way to programmatically solve this. But for example, I might try plugging in x = 10, which equals:

4000 = ((2000000 / 5) / 10) / 10

Then 2¹⁰ = 1024 which is decently close to 4000, but I don't know what would be closer. Trying x = 11 gives:

3636 = ((2000000 / 5) / 10) / 11

And 2¹¹ = 2048, so x = 11 is a better solution.

Wondering how I can programmatically solve this. I have tried to factor the equation out, but it's been a while since I've done this so I don't know.

z = (((m / k) / j) / x)
x * z = (m / k) / j
j * (x * z) = m / k
k * (j * (x * z)) = m
...

A bit lost now, not sure how to get it to the point of this:

f(k, j) = ... => [ x, z ]

Generally I'm trying to figure out how to solve an equation programmatically. Just seeing an implementation would allow me to understand without making it too broad.

What I've been doing currently is basically going into the debugger and typing in some JavaScript to find values, but there's gotta be a better way.

enter image description here


Solution

  • You can do an iterative search:

    x = 1
    best_error = infinity
    best_x = 0
    while True:
       z = (((m / k) / j) / x)
       error = abs(z - pow(2,x))
       if error > best_error
          return best_x
       best_error = error
       best_x = x
       x = x+1
    

    For other relationships there are better ways of choosing the next x, but for this particular problem a linear search seems fine.