numpy多项式TypeError

时间:2017-11-13 15:24:11

标签: python numpy

我正在使用python 3.6.3。我想用值列表调用多项式,但我得到了一个TypeError。

Python 3.6.3 (v3.6.3:2c5fed8, Oct  3 2017, 18:11:49) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from numpy.polynomial import Polynomial
>>> p = Polynomial([-3, 2, 0, 1])
>>> p(0)
-3.0
>>> p([1, 2, 3])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\Michel\AppData\Local\Programs\Python\Python36\lib\site-packages\numpy\polynomial\_polybase.py", line 292, in __call__
    arg = off + scl*arg
TypeError: 'numpy.float64' object cannot be interpreted as an integer
>>> p([1.0, 2.0, 3.0])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\Michel\AppData\Local\Programs\Python\Python36\lib\site-packages\numpy\polynomial\_polybase.py", line 292, in __call__
    arg = off + scl*arg
TypeError: 'numpy.float64' object cannot be interpreted as an integer
>>>

我在网上找不到任何相关主题。 知道遗失了什么?

2 个答案:

答案 0 :(得分:3)

鉴于你已经导入了numpy,将你的值列表粘贴到数组中应该不是问题:

>>> p(numpy.array([1, 2, 3]))
array([  0.,   9.,  30.])

答案 1 :(得分:1)

您可以通过传递值列表来构造多项式:

f = Polynomial([1, 2, 3])  # means 1 + 2 * x + 3 * x^2

您可以通过将数字作为参数来计算多项式的值:

In [8]: f(1.5)
Out[8]: 10.75

但是你不能将列表作为参数传递。 如果要检索列表中每个元素的值,则应使用此代码或类似的代码:

In [9]: [f(i) for i in [1.0, 2.0, 3.0]]
Out[9]: [6.0, 17.0, 34.0]