Find roots of a function a x^n + bx - c = 0 where n isn't an integer with Numpy?

放肆的年华 提交于 2019-12-04 04:23:31

I think your beast choice is scipy.optimize.brentq():

def f(x, n, a, b, c):
    return a * x**n + b * x - c

print scipy.optimize.brentq(
    f, 0.0, 100.0, args=(77.0/27.0, 1.0, 1.0, 10.0))

prints

2.0672035922580592

Look here and here.

I'm so proud of myself, I still remember the specifics (without reading the link!) :)

If you don't get that, look here.

I would use fsolve from scipy,

from scipy.optimize import fsolve

def func(x,a,b,c,n):
    return a*x**n + b*x - c

a,b,c = 11.,23.,31.

n = 77./27.

guess = [4.0,]    

print fsolve(func,guess,args=(a,b,c,n)) # 0.94312258329

This of course gives you a root, not necessarily all roots.


Edit: Use brentq, it's much faster

from timeit import timeit

sp = """
from scipy.optimize import fsolve
from scipy.optimize import brentq

from numpy.random import uniform
from numpy import zeros

m = 10**3

z = zeros((m,4))
z[:,:3] = uniform(1,50,size=(m,3))
z[:,3] = uniform(1,10,m)

def func(x,a,b,c,n):
    return a*x**n + b*x - c

"""

s = "[fsolve(func,1.0,args=tuple(i)) for i in z]"
t = "[brentq(func,0.,10.,args=tuple(i)) for i in z]"

runs = 10**2

print 'fsolve\t', timeit(s,sp,number=runs)
print 'brentq\t', timeit(t,sp,number=runs)

gives me,

fsolve  15.5562820435
brentq  3.84963393211

You need a root finding algorithm like Newton's method. All root finding algorithms will work with non-integer powers. They need not even be rational numbers.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!