sbe*_*idy 7 python equation numpy
我正在用python编写程序,在其中我需要找到一个函数的根源:
a*x^n + b*x -c = 0
Run Code Online (Sandbox Code Playgroud)
where a
和b
是在程序中先前计算过的常量,但是有几千个.我需要对所有的值重复这个等式,a
并且b
一次使用n = 77/27
和一次n = 3
.
我怎么能在python中做到这一点?我检查过numpy.roots(p)
,这会在n = 3
我想的时候起作用.但是n = 77/27
我怎么能这样做呢?
我认为你的野兽选择是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))
Run Code Online (Sandbox Code Playgroud)
版画
2.0672035922580592
Run Code Online (Sandbox Code Playgroud)
我会用fsolve
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
Run Code Online (Sandbox Code Playgroud)
当然,这为您提供了一个根,不一定是所有根。
编辑:使用brentq
,速度更快
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)
Run Code Online (Sandbox Code Playgroud)
给我,
fsolve 15.5562820435
brentq 3.84963393211
Run Code Online (Sandbox Code Playgroud)