本文整理汇总了Python中numpy.roots方法的典型用法代码示例。如果您正苦于以下问题:Python numpy.roots方法的具体用法?Python numpy.roots怎么用?Python numpy.roots使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类numpy
的用法示例。
在下文中一共展示了numpy.roots方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: fit_cubic
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import roots [as 别名]
def fit_cubic(y0, y1, g0, g1):
"""Fit cubic polynomial to function values and derivatives at x = 0, 1.
Returns position and function value of minimum if fit succeeds. Fit does
not succeeds if
1. polynomial doesn't have extrema or
2. maximum is from (0,1) or
3. maximum is closer to 0.5 than minimum
"""
a = 2 * (y0 - y1) + g0 + g1
b = -3 * (y0 - y1) - 2 * g0 - g1
p = np.array([a, b, g0, y0])
r = np.roots(np.polyder(p))
if not np.isreal(r).all():
return None, None
r = sorted(x.real for x in r)
if p[0] > 0:
maxim, minim = r
else:
minim, maxim = r
if 0 < maxim < 1 and abs(minim - 0.5) > abs(maxim - 0.5):
return None, None
return minim, np.polyval(p, minim)
示例2: data_analysis
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import roots [as 别名]
def data_analysis(e_ph, flux, method="least"):
if method == "least":
coeffs = np.polyfit(x=e_ph, y=flux, deg=11)
polynom = np.poly1d(coeffs)
x = np.linspace(e_ph[0], e_ph[-1], num=100)
pd = np.polyder(polynom, m=1)
indx = np.argmax(np.abs(pd(x)))
eph_c = x[indx]
pd2 = np.polyder(polynom, m=2)
p2_roots = np.roots(pd2)
p2_roots = p2_roots[p2_roots[:].imag == 0]
p2_roots = np.real(p2_roots)
Eph_fin = find_nearest(p2_roots,eph_c)
return Eph_fin, polynom
elif method == "new method":
pass
#plt.plot(Etotal, total, "ro")
#plt.plot(x, polynom(x))
示例3: impz
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import roots [as 别名]
def impz(b,a):
"""Pseudo implementation of the impz method of MATLAB"""
#% Compute time vector
# M = 0; NN = [];
# if isempty(N)
# % if not specified, determine the length
# if isTF
# N = impzlength(b,a,.00005);
# else
# N = impzlength(b,.00005);
# end
p = np.roots(a)
N = stableNmarginal_length(p, 0.00005, 0)
N = len(b) * len(b) * len(b) # MATLAB AUTOFINDS THE SIZE HERE...
#TODO: Implement some way of finding the autosieze of this... I used a couple of examples... matlab gave 43 as length we give 64
x = zeros(N)
x[0] = 1
h = lfilter(b,a, x)
return h
示例4: polyroots
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import roots [as 别名]
def polyroots(p, realroots=False, condition=lambda r: True):
"""
Returns the roots of a polynomial with coefficients given in p.
p[0] * x**n + p[1] * x**(n-1) + ... + p[n-1]*x + p[n]
INPUT:
p - Rank-1 array-like object of polynomial coefficients.
realroots - a boolean. If true, only real roots will be returned and the
condition function can be written assuming all roots are real.
condition - a boolean-valued function. Only roots satisfying this will be
returned. If realroots==True, these conditions should assume the roots
are real.
OUTPUT:
A list containing the roots of the polynomial.
NOTE: This uses np.isclose and np.roots"""
roots = np.roots(p)
if realroots:
roots = [r.real for r in roots if isclose(r.imag, 0)]
roots = [r for r in roots if condition(r)]
duplicates = []
for idx, (r1, r2) in enumerate(combinations(roots, 2)):
if isclose(r1, r2):
duplicates.append(idx)
return [r for idx, r in enumerate(roots) if idx not in duplicates]
示例5: get_minimum_energy_path
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import roots [as 别名]
def get_minimum_energy_path(self, pressure=None):
"""
Args:
pressure:
Returns:
"""
if pressure is not None:
raise NotImplemented()
v_min_lst = []
for c in self._coeff.T:
v_min = np.roots(np.polyder(c, 1))
p_der2 = np.polyder(c, 2)
p_val2 = np.polyval(p_der2, v_min)
v_m_lst = v_min[p_val2 > 0]
if len(v_m_lst) > 0:
v_min_lst.append(v_m_lst[0])
else:
v_min_lst.append(np.nan)
return np.array(v_min_lst)
示例6: roots_of_characteristic
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import roots [as 别名]
def roots_of_characteristic(self):
"""
This function calculates z_0 and the 2m roots of the characteristic equation
associated with the Euler equation (1.7)
Note:
------
numpy.poly1d(roots, True) defines a polynomial using its roots that can be
evaluated at any point. If x_1, x_2, ... , x_m are the roots then
p(x) = (x - x_1)(x - x_2)...(x - x_m)
"""
m = self.m
ϕ = self.ϕ
# Calculate the roots of the 2m-polynomial
roots = np.roots(ϕ)
# sort the roots according to their length (in descending order)
roots_sorted = roots[np.argsort(abs(roots))[::-1]]
z_0 = ϕ.sum() / np.poly1d(roots, True)(1)
z_1_to_m = roots_sorted[:m] # we need only those outside the unit circle
λ = 1 / z_1_to_m
return z_1_to_m, z_0, λ
示例7: test_output_order
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import roots [as 别名]
def test_output_order(self):
zc, zr = _cplxreal(np.roots(array([1, 0, 0, 1])))
assert_allclose(np.append(zc, zr), [1/2 + 1j*sin(pi/3), -1])
eps = spacing(1)
a = [0+1j, 0-1j, eps + 1j, eps - 1j, -eps + 1j, -eps - 1j,
1, 4, 2, 3, 0, 0,
2+3j, 2-3j,
1-eps + 1j, 1+2j, 1-2j, 1+eps - 1j, # sorts out of order
3+1j, 3+1j, 3+1j, 3-1j, 3-1j, 3-1j,
2-3j, 2+3j]
zc, zr = _cplxreal(a)
assert_allclose(zc, [1j, 1j, 1j, 1+1j, 1+2j, 2+3j, 2+3j, 3+1j, 3+1j,
3+1j])
assert_allclose(zr, [0, 0, 1, 2, 3, 4])
z = array([1-eps + 1j, 1+2j, 1-2j, 1+eps - 1j, 1+eps+3j, 1-2*eps-3j,
0+1j, 0-1j, 2+4j, 2-4j, 2+3j, 2-3j, 3+7j, 3-7j, 4-eps+1j,
4+eps-2j, 4-1j, 4-eps+2j])
zc, zr = _cplxreal(z)
assert_allclose(zc, [1j, 1+1j, 1+2j, 1+3j, 2+3j, 2+4j, 3+7j, 4+1j,
4+2j])
assert_equal(zr, [])
示例8: __init__
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import roots [as 别名]
def __init__(self, recording, freq_min=300, freq_max=6000, freq_wid=1000, filter_type='fft', order=3,
chunk_size=30000, cache_chunks=False):
assert HAVE_BFR, "To use the BandpassFilterRecording, install scipy: \n\n pip install scipy\n\n"
self._freq_min = freq_min
self._freq_max = freq_max
self._freq_wid = freq_wid
self._type = filter_type
self._order = order
self._chunk_size = chunk_size
if self._type == 'butter':
fn = recording.get_sampling_frequency() / 2.
band = np.array([self._freq_min, self._freq_max]) / fn
self._b, self._a = ss.butter(self._order, band, btype='bandpass')
if not np.all(np.abs(np.roots(self._a)) < 1):
raise ValueError('Filter is not stable')
FilterRecording.__init__(self, recording=recording, chunk_size=chunk_size, cache_chunks=cache_chunks)
self.copy_channel_properties(recording)
self.is_filtered = True
self._kwargs = {'recording': recording.make_serialized_dict(), 'freq_min': freq_min, 'freq_max': freq_max,
'freq_wid': freq_wid, 'filter_type': filter_type, 'order': order,
'chunk_size': chunk_size, 'cache_chunks': cache_chunks}
示例9: _v
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import roots [as 别名]
def _v(self, P, T, phi_w):
"""Calculate the real volume of a humid air using the virial equation
of state
Parameters
----------
T : float
Temperature, [K]
phi_w : float
Molar fraction of water, [-]
Returns
-------
"""
vir = self._virialMixture(T, phi_w)
Bm = vir["Bm"]
Cm = vir["Cm"]
vm = roots([1, -R*T/P, -R*T*Bm/P, -R*T*Cm/P])
if vm[0].imag == 0.0:
v = vm[0].real
else:
v = vm[2].real
return v
示例10: poly2lsf
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import roots [as 别名]
def poly2lsf(a):
a = a / a[0]
A = np.r_[a, 0.0]
B = A[::-1]
P = A - B
Q = A + B
P = deconvolve(P, np.array([1.0, -1.0]))[0]
Q = deconvolve(Q, np.array([1.0, 1.0]))[0]
roots_P = np.roots(P)
roots_Q = np.roots(Q)
angles_P = np.angle(roots_P[::2])
angles_Q = np.angle(roots_Q[::2])
angles_P[angles_P < 0.0] += np.pi
angles_Q[angles_Q < 0.0] += np.pi
lsf = np.sort(np.r_[angles_P, angles_Q])
return lsf
示例11: get_mu_tensor
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import roots [as 别名]
def get_mu_tensor(self):
const_fact = self._dist_to_opt_avg**2 * self._h_min**2 / 2 / self._grad_var
coef = tf.Variable([-1.0, 3.0, 0.0, 1.0], dtype=tf.float32, name="cubic_solver_coef")
coef = tf.scatter_update(coef, tf.constant(2), -(3 + const_fact) )
roots = tf.py_func(np.roots, [coef], Tout=tf.complex64, stateful=False)
# filter out the correct root
root_idx = tf.logical_and(tf.logical_and(tf.greater(tf.real(roots), tf.constant(0.0) ),
tf.less(tf.real(roots), tf.constant(1.0) ) ), tf.less(tf.abs(tf.imag(roots) ), 1e-5) )
# in case there are two duplicated roots satisfying the above condition
root = tf.reshape(tf.gather(tf.gather(roots, tf.where(root_idx) ), tf.constant(0) ), shape=[] )
tf.assert_equal(tf.size(root), tf.constant(1) )
dr = self._h_max / self._h_min
mu = tf.maximum(tf.real(root)**2, ( (tf.sqrt(dr) - 1)/(tf.sqrt(dr) + 1) )**2)
return mu
示例12: get_speed
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import roots [as 别名]
def get_speed(power,Cx,f,W,slope,headwind,elevation):
# slope in percent
# headwind in m/s at 10 m high
# elevation in meters
air_pressure = 1 - 0.000104 * elevation
Cx = Cx*air_pressure
G = 9.81
headwind = (0.1**0.143) * headwind
roots = np.roots([Cx, 2*Cx*headwind, Cx*headwind**2 + W*G*(slope/100.0+f), -power])
roots = np.real(roots[np.imag(roots) == 0])
roots = roots[roots>0]
speed = np.min(roots)
if speed + headwind < 0:
roots = np.roots([-Cx, -2*Cx*headwind, -Cx*headwind**2 + W*G*(slope/100.0+f), -power])
roots = np.real(roots[np.imag(roots) == 0])
roots = roots[roots>0]
if len(roots) > 0:
speed = np.min(roots)
return speed
示例13: stroud_1966_2
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import roots [as 别名]
def stroud_1966_2(n):
degree = 3
# r is a smallest real-valued root of a polynomial of degree 3
rts = numpy.roots(
[2 * (n - 2) * (n + 1) * (n + 3), -(5 * n ** 2 + 5 * n - 18), 4 * n, -1]
)
r = numpy.min([r.real for r in rts if abs(r.imag) < 1.0e-15])
s = 1 - n * r
t = 0.5
B = (n - 2) / (1 - 2 * n * r ** 2 - 2 * (1 - n * r) ** 2) / (n + 1) / (n + 2)
C = 2 * (1 / (n + 1) - B) / n
data = [(B, rd(n + 1, [(r, n), (s, 1)])), (C, rd(n + 1, [(t, 2)]))]
points, weights = untangle(data)
return TnScheme("Stroud 1966-II", n, weights, points, degree, source)
示例14: phormants
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import roots [as 别名]
def phormants(x, sampling_rate):
N = len(x)
w = np.hamming(N)
# Apply window and high pass filter.
x1 = x * w
x1 = lfilter([1], [1., 0.63], x1)
# Get LPC.
ncoeff = 2 + sampling_rate / 1000
A, e, k = lpc(x1, ncoeff)
# A, e, k = lpc(x1, 8)
# Get roots.
rts = np.roots(A)
rts = [r for r in rts if np.imag(r) >= 0]
# Get angles.
angz = np.arctan2(np.imag(rts), np.real(rts))
# Get frequencies.
frqs = sorted(angz * (sampling_rate / (2 * math.pi)))
return frqs
示例15: tune_everything
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import roots [as 别名]
def tune_everything(self, x0squared, c, t, gmin, gmax):
del t
# First tune based on dynamic range
if c == 0:
dr = gmax / gmin
mustar = ((np.sqrt(dr) - 1) / (np.sqrt(dr) + 1))**2
alpha_star = (1 + np.sqrt(mustar))**2/gmax
return alpha_star, mustar
dist_to_opt = x0squared
grad_var = c
max_curv = gmax
min_curv = gmin
const_fact = dist_to_opt * min_curv**2 / 2 / grad_var
coef = [-1, 3, -(3 + const_fact), 1]
roots = np.roots(coef)
roots = roots[np.real(roots) > 0]
roots = roots[np.real(roots) < 1]
root = roots[np.argmin(np.imag(roots))]
assert root > 0 and root < 1 and np.absolute(root.imag) < 1e-6
dr = max_curv / min_curv
assert max_curv >= min_curv
mu = max(((np.sqrt(dr) - 1) / (np.sqrt(dr) + 1))**2, root**2)
lr_min = (1 - np.sqrt(mu))**2 / min_curv
alpha_star = lr_min
mustar = mu
return alpha_star, mustar