0

I am trying to solve the equation: log(1+x)/x - 1/(1+x) == 2/3 * q * x**2 for x with q = 4e-4

I tried

import numpy as np
import scipy.optimize as so
q = 4e-4
eqn = lambda x: np.log(1+x) / x  -  1 / (1+x)   -   2/3 * q * x**2 
sol = so.fsolve(eqn, 1)[0]
print(sol)

and

q = 4e-4
eqn = lambda x: np.log(1+x) / x  -  1 / (1+x)   -   2/3 * q * x**2 
sol = so.root_scalar(eqn, bracket=(1e-6, 1e20)).root
print(sol)

but get absurd answers.

I tried plotting the equation as follows: enter image description here

I am expecting the answer to be x ~ 20. How do I get this?

Matrix23
  • 103
  • 4
  • 1
    Your starting guesses are to the left side of the inflection point, so the solvers go in the wrong direction. Make your starting guess 3 and it converges. – Tim Roberts Aug 08 '23 at 03:31

2 Answers2

3

These algorithms work best when you provide a good initial guess or a tighter bracket.

import numpy as np
from scipy.optimize import fsolve, root_scalar, root

def eqn(x): 
    q = 4e-4
    return np.log(1+x)/x - 1/(1+x) - 2/3*q*x**2


sol_fsolve = fsolve(eqn, 10)[0]
sol_rootscalar = root_scalar(eqn, bracket=(1e-6, 100)).root
sol_root = root(eqn, 10).x[0]

print(sol_fsolve)       # 19.84860182482322
print(sol_rootscalar)   # 19.848601824823366
print(sol_root)         # 19.84860182482322
jared
  • 4,165
  • 1
  • 8
  • 31
1

just modify the init value of x may help

import numpy as np
import scipy.optimize as so

q = 4e-4
eqn = lambda x: np.log(1+x) / x  -  1 / (1+x)   -   2/3 * q * x**2 
sol = so.fsolve(eqn, [15])[0]
print(sol)

will output

19.848601824823362
Xiaomin Wu
  • 400
  • 1
  • 5