[英]Does poly function accept only the list as its 1st argument when I tried to pass an numpy array as an 1st argument it is showing an error
Does poly function accept only the list as its 1st argument when I tried to pass an numpy array as an 1st argument it is not working. 当我尝试将numpy数组作为第一参数传递时,poly函数是否仅将列表作为其第一参数接受,因此它不起作用。
import numpy
A=list(map(float,raw_input().split()))
k=int(raw_input())
print numpy.polyval(A,k)
The above code works but 上面的代码有效,但是
import numpy
A=numpy.array([raw_input().split()],float)
k=int(raw_input())
print k,A
print numpy.polyval(A,k)
The above code does not work 上面的代码不起作用
import numpy
A=numpy.array([raw_input().split()],float)
k=int(raw_input())
print k,A
print numpy.polyval(A,k)
from the docs , in numpy.polyval(p, x)
, p
must be a 1d array of an array-like (such as list of numbers). 从docs开始 ,在
numpy.polyval(p, x)
, p
必须是类似数组的一维数组(例如数字列表)。
in your first code, A
is a list of numbers, which satisfies the above condition. 在您的第一个代码中,
A
是一个满足上述条件的数字列表。 result when test it: 测试时的结果:
>>> import numpy
>>> A=list(map(float,raw_input().split()))
1 2 3 5
>>> k=int(raw_input())
5
>>> print numpy.polyval(A,k)
195.0
>>> A # show how A looks like
[1.0, 2.0, 3.0, 5.0]
in your second code, your A
is a 1x4 2d array, take a look at what polyval()
returns: 在第二个代码中,您的
A
是一个1x4 2d数组,请看一下polyval()
返回的内容:
p[0]*x**(N-1) + p[1]*x**(N-2) + ... + p[N-2]*x + p[N-1]
since A.shape[0] == 1
, it will only returns p[N-1]
, which is an array of coefficients. 由于
A.shape[0] == 1
,它将仅返回p[N-1]
,它是一个系数数组。
>>> import numpy
>>> A=numpy.array([raw_input().split()],float)
1 2 3 5
>>> k=int(raw_input())
5
>>> print k,A
5 [[1. 2. 3. 5.]]
>>> print numpy.polyval(A,k)
[1. 2. 3. 5.]
another example: 另一个例子:
>>> import numpy
>>> a = numpy.array([[1, 2], [10, 20]])
>>> a
array([[ 1, 2],
[10, 20]])
>>> k = int(raw_input())
3
>>> numpy.polyval(a, k)
array([13, 26])
explanation of result: 结果说明:
13 = 1 * 3 + 10
26 = 2 * 3 + 20
array([13, 26]) = a[0] * k**1 + a[1]
solution: remove the braces []
: 解决方案:删除括号
[]
:
import numpy
>>> A=numpy.array(raw_input().split(),float)
1 2 3 5
>>> A
array([1., 2., 3., 5.])
>>> k = int(raw_input())
5
>>> print numpy.polyval(A,k)
195.0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.