﻿ Python相当于R poly()函数？ - 代码日志

#### Python相当于R poly()函数？

``````a <- c(1:10)
``````

``````polynomial <- poly(a, 3)
``````

``````              1           2          3
[1,] -0.49543369  0.52223297 -0.4534252
[2,] -0.38533732  0.17407766  0.1511417
[3,] -0.27524094 -0.08703883  0.3778543
[4,] -0.16514456 -0.26111648  0.3346710
[5,] -0.05504819 -0.34815531  0.1295501
[6,]  0.05504819 -0.34815531 -0.1295501
[7,]  0.16514456 -0.26111648 -0.3346710
[8,]  0.27524094 -0.08703883 -0.3778543
[9,]  0.38533732  0.17407766 -0.1511417
[10,]  0.49543369  0.52223297  0.4534252
``````

``````import numpy as np

def poly(x, p):
x = np.array(x)
X = np.transpose(np.vstack((x**k for k in range(p+1))))
return np.linalg.qr(X)[0][:,1:]
``````

``````In [29]: poly([1,2,3,4,5,6,7,8,9,10], 3)
Out[29]:
array([[-0.49543369,  0.52223297,  0.45342519],
[-0.38533732,  0.17407766, -0.15114173],
[-0.27524094, -0.08703883, -0.37785433],
[-0.16514456, -0.26111648, -0.33467098],
[-0.05504819, -0.34815531, -0.12955006],
[ 0.05504819, -0.34815531,  0.12955006],
[ 0.16514456, -0.26111648,  0.33467098],
[ 0.27524094, -0.08703883,  0.37785433],
[ 0.38533732,  0.17407766,  0.15114173],
[ 0.49543369,  0.52223297, -0.45342519]])

In [30]:
``````