RuntimeWarning: invalid value encountered in power scipy.optimize root

189 Views Asked by At

basically I am trying to reproduce an example from a website because I want to find the equivalent to the R uniroot for python. I found a blog entry (https://waterprogramming.wordpress.com/2016/08/18/root-finding-in-matlab-r-python-and-c/) where the person manages to achieve that. In R, they do

b <- 0.42
q <- 2.0
pcrit <- uniroot(function(x) x^q/(1+x^q) - b*x, c(0.01, 1.5))$root

and pcrit will be 0.5445145. When I try their equivalent for python,

from scipy.optimize import root
b = 0.42
q = 2.0
pcrit = root(lambda x: x**(1+x**q) - b*x, 0.75)

I first get a warning,

RuntimeWarning: invalid value encountered in power

and I'm assuming it is because numpy does not allow fractional powers of negative numbers (?). The snippet does give a result,

    fjac: array([[-1.]])
     fun: array([0.12043511])
 message: 'The iteration is not making good progress, as measured by the \n  improvement from the last ten iterations.'
    nfev: 14
     qtf: array([-0.12043511])
       r: array([nan])
  status: 5
 success: False
       x: array([0.24043343])

where pcrit.x = 0.24043343, so != 0.5445145 which is what I got for R. Either way, clearly the root finding wasn't successful according to the message and the success statement. How can I get the python snippet to reproduce the R solution? I tried the different solvers in the scipty.optimize module but without success.

Thank you for your help!

0

There are 0 best solutions below