0

I have an equation 'a*x+logx-b=0,(a and b are constants)', and I want to solve x. The problem is that I have numerous constants a(accordingly numerous b). How do I solve this equation by using python?

Maria Zverina
  • 10,863
  • 3
  • 44
  • 61
Wang
  • 11
  • 2
  • 1
    This is hard problem - see http://math.stackexchange.com/questions/433717/how-to-solve-equations-with-logarithms-like-this-ax-b-logx-c-0 – Maria Zverina Nov 03 '14 at 19:02
  • See http://en.wikipedia.org/wiki/Transcendental_equation for general approaches to solving transcedental equations – Maria Zverina Nov 03 '14 at 19:06
  • Finally numerical approach for solving transcedental equations in python is here http://stackoverflow.com/questions/15649134/using-python-to-solve-a-nonlinear-equation – Maria Zverina Nov 03 '14 at 19:09
  • Let's not close this too hastily ... it's actually an interesting question – Maria Zverina Nov 03 '14 at 19:16
  • A general remark, not addressed to anyone in particular: plotting `-log(x)` and `a*x-b` against a logarithmic x axis one can see that there is exactly one real solution for `a!<0` and either two real solutions (possibly a double solution) or zero solutions for `a<0`. @Wang, is it safe to assume that yours `a` are never negative? – gboffi Nov 03 '14 at 20:46

2 Answers2

1

You could check out something like

http://docs.scipy.org/doc/scipy-0.13.0/reference/optimize.nonlin.html

which has tools specifically designed for these kinds of equations.

AureliusPhi
  • 433
  • 2
  • 12
0

Cool - today I learned about Python's numerical solver.

from math import log
from scipy.optimize import brentq

def f(x, a, b):

    return a * x + log(x) - b


for a in range(1,5):
    for b in range(1,5):
        result = brentq(lambda x:f(x, a, b), 1e-10, 20)
        print a, b, result

brentq provides estimate where the function crosses the x-axis. You need to give it two points, one which is definitely negative and one which is definitely positive. For negative point choose number that is smaller than exp(-B), where B is maximum value of b. For positive point choose number that's bigger than B.

If you cannot predict range of b values, you can use a solver instead. This will probably produce a solution - but this is not guaranteed.

from scipy.optimize import fsolve


for a in range(1,5):
    for b in range(1,5):
        result = fsolve(f, 1, (a,b))
        print a, b, result
Maria Zverina
  • 10,863
  • 3
  • 44
  • 61