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

偶尔善良 提交于 2019-12-05 23:06:12

问题


I'm writing a program in python and in it I need to find the roots of a function that is:

a*x^n + b*x -c = 0 

where a and b are constants that are calculated earlier in the program but there are several thousand of them. I need to repeat this equation twice for all values of a and b once with n = 77/27 and once with n = 3.

How can i do this in python? I checked numpy.roots(p) and that would work for when n = 3 I think. But for n = 77/27 how would I be able to do that?


回答1:


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



回答2:


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.




回答3:


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



回答4:


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.



来源:https://stackoverflow.com/questions/6519380/find-roots-of-a-function-a-xn-bx-c-0-where-n-isnt-an-integer-with-numpy

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