Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Solving an equation with one variable in Python

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading