Matrix23
Matrix23

Reputation: 103

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

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?

Upvotes: 0

Views: 59

Answers (2)

jared
jared

Reputation: 8981

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

Upvotes: 3

Xiaomin Wu
Xiaomin Wu

Reputation: 668

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

Upvotes: 1

Related Questions