numpy 根负指数函数

问题描述

我已经阅读了 numpy.roots,它可以计算出常见代数函数的 y 轴交点。

哪个

y = ax^n + bx^{n - 1} + cx^{n - 2} ...

指数总是自然数。

所以通过传入

[1,2,3]

我基本上在锻炼

y = x^2 + 2x + 3

但我需要引入负指数,例如

y = x^2 + 2x + 3 - x^{-1}

我想知道我是否可以为上面的实例构造一个字典

{2: 1,1: 2,0: 3,-1: 1}

哪些键是指数,哪些值是系数,并计算根。


任何建议将不胜感激。

解决方法

如果你得到一个负指数的“多项式”,它并不是真正的 多项式但是一个分数函数,所以要找到根,你可以简单地找到分子多项式的根。

在函数中

enter image description here

你可以分解出最后一项

enter image description here

等于

enter image description here

所以我们可以说

enter image description here

函数 g(x) 是 n+m 次多项式,找到 g(x) 的根,你将得到 f(x) 的根,因为分母不能为零(x=0 是在 f(x) 的域之外,当它为零时,你会得到一个奇点,在这种情况下,除以零是不可能的)。

编辑

我们可以图形化验证。例如,让我们用这些系数来做一个函数

import numpy as np
coeffs = [1,6,-6,-64,-27,90]
roots = np.roots(coeffs)
roots

array([-5.,3.,-3.,-2.,1.])

如你所见,我们得到了 5 个真正的根。

现在让我们用给定的系数和分数函数定义多项式

import matplotlib.pyplot as plt

def print_func(func,func_name):
    fig,ax = plt.subplots(figsize=(12,.5))
    ax.set_xticks([])
    ax.set_yticks([])
    ax.axis('off')
    ax.text(0,.5,f"{func_name}\n"
            fr"${func}$",fontsize=15,va='center'
           )
    plt.show()

def polynom(x,coeffs):
    res = 0
    terms = []
    for t,c in enumerate(coeffs[::-1]):
        res += c * x**t
        terms.append(f"{c:+} x^{{{t}}}")
    func = "".join(terms[::-1])
    print_func(func,"polynomial")
    return res

def fract(x,coeffs,min_exp):
    res = 0
    terms = []
    for t,c in enumerate(coeffs[::-1]):
        e = t + min_exp
        res += c * x**e
        terms.append(f"{c:+} x^{{{e}}}")
    func = "".join(terms[::-1])
    print_func(func,"fractional")
    return res

x = np.linspace(-6,4,100)

这就是多项式

y1 = polynom(x,coeffs)

enter image description here

这是小数函数

y2 = fract(x,-2)

enter image description here

让我们绘制它们和找到的根

plt.plot(x,y1,label='polynomial')
plt.plot(x,y2,label='fractional')
plt.axhline(0,color='k',ls='--',lw=1)
plt.plot(roots,np.repeat(0,roots.size),'o',label='roots')
plt.ylim(-100,100)
plt.legend()
plt.show()

enter image description here

你看他们有相同的根源。

请注意,如果你有一个喜欢的分数

y2 = fract(x,-3)

enter image description here

即分母有一个奇数指数,你可以认为 x=0 也有根,只需看图

enter image description here

但这不是根,而是奇点,是±∞ 的垂直渐近线。指数分母为偶数时,奇点将趋向 +∞。