scipy.optimize.newton, How to declare the derivative?

0

Of the libreria Scipy to use the metodo de Newton I have to declare the functions and the parameters scipy.optimize.newton(func, x0, fprime=None, args=(), tol=1.48e-08, maxiter=50, fprime2=None) The problem is that when I declare in the field of fprime as my derivative p the code does not run. I think the problem is in how the arguments are being declared, but I can not find the error I place the code:

import itertools
import numpy as np
from scipy import optimize
from scipy import integrate

n=763.0; s=762.0; b=0.0026; y=0.5673
def p(x,b,n,y,s): return 1.0/(x*(b*n+y*np.log(x)-s*b*x))
def Ui(x,x1,b,n,y,s): return (integrate.fixed_quad(p, x, x1, args=(b,n,y,s),    n=5)[0]-1.0)

From optimize.newton I call in the third field to the derivative that is my function p and the code does not run.

def t(x,x1,b,n,y,s): return optimize.newton(Ui, x1, p, args=(x,b,n,y,s),  maxiter=500)
x=0.99;  x1=1.0
X=[1]                
for _ in xrange(1,15): x1=round(t(x1,x, b, n, y, s),500); x=x1; X.append(x)
Xu = X[1:]

If I do not declare p the used method is secant, and there the code if it runs, but it is necessary for me to have a better approximation to declare the derivative.

Newton Method in Scipy

    
asked by Santiago Yepes 28.03.2017 в 17:42
source

1 answer

1

The arguments you pass in the tuple args of the method optimize.newton are used for both the function and its derivative. The problem is that your function has one more parameter ( x1 ) than its derivative. This will give you an error something like this:

  

TypeError: p () takes exactly 5 arguments (6 given)

The simple solution would be to pass that parameter to the derivative p even if it is not used at all in the function itself:

import itertools
import numpy as np
from scipy import optimize
from scipy import integrate

n=763.0; s=762.0; b=0.0026; y=0.5673
def p(x,x1,b,n,y,s):
    return 1.0/(x*(b*n+y*np.log(x)-s*b*x))
def Ui(x,x1,b,n,y,s): return (integrate.fixed_quad(p, x, x1, args=(x1,b,n,y,s),    n=5)[0]-1.0)
def t(x,x1,b,n,y,s): return optimize.newton(Ui, x1, p, args=(x1,b,n,y,s,),  maxiter=500)

x=0.99;  x1=1.0
X=[1]                
for _ in xrange(1,15):
    x1=round(t(x1,x, b, n, y, s),500)
    x=x1
    X.append(x)
    Xu = X[1:]
    
answered by 28.03.2017 / 18:08
source