获取多项式 X 在 Y 处的值?(Python 3.10,NumPy)

huangapple go评论87阅读模式
英文:

Get Polynomial X at Y? (Python 3.10, NumPy)

问题

我试图计算Python 3.10中以降序系数顺序给定的多项式在特定Y值处的所有可能的实X值。我希望将得到的X值提供给我,以列表的形式。

我尝试使用numpy库的roots()函数,如这个帖子中的一个答案所示,但似乎不起作用:

import numpy as np
import matplotlib.pyplot as plt

def main():
    coeffs = np.array([1, 2, 2])
    y = 1.5

    polyDataX = np.linspace(-2, 0)
    polyDataY = np.empty(shape = len(polyDataX), dtype = float)

    for i in range(len(polyDataX)):
        polyDataY[i] = coeffs[0] * pow(polyDataX[i], 2) + coeffs[1] * polyDataX[i] + coeffs[2]

    coeffs[-1] -= y
    x = np.roots(coeffs).tolist()

    plt.axhline(y, color = "orange")
    plt.plot(polyDataX, polyDataY, color = "blue")
    plt.title("X = " + str(x))
    plt.show()
    plt.close()
    plt.clf()

if (__name__ == "__main__"):
    main()

在上面的示例中,我将多项式的系数存储在名为coeffs的本地变量中,以降序排列。然后,我尝试收集所有Y值为0.5的X值,分别存储在xy本地变量中。然后,将收集到的X值显示为所示图的标题。

上面的脚本会生成以下图表:
获取多项式 X 在 Y 处的值?(Python 3.10,NumPy)

而正确的X值应该是:
获取多项式 X 在 Y 处的值?(Python 3.10,NumPy)

在Python中,获取多项式在特定Y值处的所有实际X值的正确方法是什么?

感谢阅读我的帖子,任何指导都将不胜感激。

英文:

I'm attempting to calculate all possible real X-values at a certain Y-value from a polynomial given in descending coefficent order, in Python 3.10. I want the resulting X-values to be provided to me in a list.

I've tried using the roots() function of the numpy library, as shown in one of the answers to this post, however it does not appear to work:

import numpy as np
import matplotlib.pyplot as plt

def main():
    coeffs = np.array([1, 2, 2])
    y = 1.5

    polyDataX = np.linspace(-2, 0)
    polyDataY = np.empty(shape = len(polyDataX), dtype = float)

    for i in range(len(polyDataX)):
        polyDataY[i] = coeffs[0] * pow(polyDataX[i], 2) + coeffs[1] * polyDataX[i] + coeffs[2]

    coeffs[-1] -= y
    x = np.roots(coeffs).tolist()

    plt.axhline(y, color = "orange")
    plt.plot(polyDataX, polyDataY, color = "blue")
    plt.title("X = " + str(x))
    plt.show()
    plt.close()
    plt.clf()

if (__name__ == "__main__"):
    main()

In my example above, I have the coefficents of my polynomial stored in the local variable coeffs, in descending order. I then attempt to gather all the X-values at the Y-value of 0.5, stored within the x and y local variables respectivelly. I then display the gathered X-values as the title of the shown plot.

The script above results in the following plot:
获取多项式 X 在 Y 处的值?(Python 3.10,NumPy)

With the X-values being shown as [-2.0, 0.0], instead of the correct:
获取多项式 X 在 Y 处的值?(Python 3.10,NumPy)

What is the proper way to get all real X-values of a polynomial at a certain Y-value in Python?

Thanks for reading my post, any guidance is appreciated.

答案1

得分: 3

你的代码是正确的,你使用了根函数的正确方法。只有一个小问题涉及到数据类型。你可以通过调试器或在coeffs[-1] -= y之后打印coeff来看到错误。在你的代码coeffs = np.array([1, 2, 2])中,numpy将创建一个具有整数类型的数组,因此你的减法操作,应该得到0.5实际上得到0,所以你的系数变成了[1, 2, 0]。对于这些值,将计算出正确的结果。因此,我们只需要将数据类型设置为浮点数:

import numpy as np
import matplotlib.pyplot as plt

def main():
    coeffs = np.array([1, 2, 2], dtype=float)   #<-----------
    y = 1.5

    polyDataX = np.linspace(-2, 0)
    polyDataY = np.empty(shape = len(polyDataX), dtype = float)

    for i in range(len(polyDataX)):
        polyDataY[i] = coeffs[0] * pow(polyDataX[i], 2) + coeffs[1] * polyDataX[i] + coeffs[2]

    coeffs[-1] -= y
    x = np.roots(coeffs).tolist()

    plt.axhline(y, color = "orange")
    plt.plot(polyDataX, polyDataY, color = "blue")
    plt.title("X = " + str(x))
    plt.show()
    plt.close()
    plt.clf()

if __name__ == "__main__":
    main()
英文:

Your code is correct and you are using the root function correctly. There is only a small issue with datatypes.
You can see the error with a debugger or by printing coeff after coeffs[-1] -= y. At your line coeffs = np.array([1, 2, 2]), numpy will create the array with an integer type and therefore your subtraction, which should result in 0.5 actually results in 0, so your coefficients become [1, 2, 0]. For those, the correct result is calculated. So we need to simply set the dtype to float:

import numpy as np
import matplotlib.pyplot as plt

def main():
    coeffs = np.array([1, 2, 2], dtype=float)   #&lt;-----------
    y = 1.5

    polyDataX = np.linspace(-2, 0)
    polyDataY = np.empty(shape = len(polyDataX), dtype = float)

    for i in range(len(polyDataX)):
        polyDataY[i] = coeffs[0] * pow(polyDataX[i], 2) + coeffs[1] * polyDataX[i] + coeffs[2]

    coeffs[-1] -= y
    x = np.roots(coeffs).tolist()

    plt.axhline(y, color = &quot;orange&quot;)
    plt.plot(polyDataX, polyDataY, color = &quot;blue&quot;)
    plt.title(&quot;X = &quot; + str(x))
    plt.show()
    plt.close()
    plt.clf()

if __name__ == &quot;__main__&quot;:
    main()

获取多项式 X 在 Y 处的值?(Python 3.10,NumPy)

答案2

得分: 2

你应该使用在numpy v1.4中添加的numpy.polynomial.Polynomial类(更多信息请参见此处)。使用该类,你可以创建一个多项式对象。要找到你的解,你可以从Polynomial对象中减去y,然后调用roots方法。另一个不错的特性是你可以直接调用该对象,这可以用来计算polyDataY

只要注意,Polynomial类期望系数是从np.roots中以相反的顺序给出的,即x^2 + 2x + 2的二次多项式应该有系数(2, 2, 1)。为了保持与你提供的内容一致,我只是传递了反转后的coeffs

import numpy as np
from numpy.polynomial import Polynomial
import matplotlib.pyplot as plt

plt.close("all")

coeffs = np.array([1, 2, 2])
poly = Polynomial(coeffs[::-1])

polyDataX = np.linspace(-2, 0)
polyDataY = poly(polyDataX)

y = 1.5
x = (poly - y).roots()
plt.axhline(y, color="orange")
plt.plot(polyDataX, polyDataY, color="blue")
plt.title("X = " + str(x))
plt.show()

获取多项式 X 在 Y 处的值?(Python 3.10,NumPy)

英文:

You should be making use of the numpy.polynomial.Polynomial class that was added in numpy v1.4 (more information here). With that class, you can create a polynomial object. To find your solution, you can subtract y from the Polynomial object and then call the roots method. Another nice feature is that you can directly call the object, which you can use to compute polyDataY.

Just note that the Polynomial class expects the coefficients to be given backward from np.roots, i.e. a quadratic of x^2 + 2x + 2 should have the coefficients (2, 2, 1). To keep things consistent with what you gave, I just pass the reversed coeffs.

import numpy as np
from numpy.polynomial import Polynomial
import matplotlib.pyplot as plt

plt.close(&quot;all&quot;)

coeffs = np.array([1, 2, 2])
poly = Polynomial(coeffs[::-1])

polyDataX = np.linspace(-2, 0)
polyDataY = poly(polyDataX)

y = 1.5
x = (poly - y).roots()
plt.axhline(y, color = &quot;orange&quot;)
plt.plot(polyDataX, polyDataY, color = &quot;blue&quot;)
plt.title(&quot;X = &quot; + str(x))
plt.show()

获取多项式 X 在 Y 处的值?(Python 3.10,NumPy)

答案3

得分: 1

The values in coeffs are int32 and the result after coeffs[-1] -= y is 0 not 0.5.

Just change coeffs = np.array([1, 2, 2]) for coeffs = np.array([1., 2., 2.])

英文:

The values in coeffs are int32 and the result after coeffs[-1] -= y is 0 not 0.5.

Just change coeffs = np.array([1, 2, 2]) for coeffs = np.array([1., 2., 2.])

huangapple
  • 本文由 发表于 2023年7月3日 18:34:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/76603915.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定