简体   繁体   中英

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.

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).

in your first code, A is a list of numbers, which satisfies the above condition. 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:

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.

>>> 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM