Python:无法将输入数组从形状(11,10)广播到形状(11)

Python:无法将输入数组从形状(11,10)广播到形状(11),python,numpy,Python,Numpy,我有一个勒让德多项式的函数,我想用牛顿的方法来求根 import numpy as np import matplotlib.pyplot as plt %matplotlib inline def Legendre(N,x): P = np.zeros((N+1,len(x))) Q = np.zeros((N+1,len(x))) P[0], P[1] = 1 + 0*x, x Q[0], Q[1] = 0 , 1 u = P[N-1] P[N] = ((2*N-

我有一个勒让德多项式的函数,我想用牛顿的方法来求根

import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline

def Legendre(N,x):
  P = np.zeros((N+1,len(x)))

  Q = np.zeros((N+1,len(x)))
  P[0], P[1] = 1 + 0*x, x
  Q[0], Q[1] = 0 , 1
  u = P[N-1]
  P[N] = ((2*N-1)*x*u-(N-1)*P[N-2])/N
  Q[N] = (2*N-1)*u+Q[N-2]
  return P,Q
要实现牛顿法:

def quadrature(N,tol=1e-19):

# Initial guess: 
i = np.arange(N)
print(i)
x = np.cos(np.pi*(4*i+3)/(4*N+2))
print(x)

eps = np.inf
iteration=0
imax = 20


while ( eps > tol ) and (iteration < imax):
    a, b =Legendre(N,x)
    negfn= -a/b
    x = x+ negfn
    iteration+=1

return x
def正交(N,tol=1e-19):
#初步猜测:
i=np.arange(N)
印刷品(一)
x=np.cos(np.pi*(4*i+3)/(4*N+2))
打印(x)
eps=np.inf
迭代=0
imax=20
而(eps>tol)和(迭代
但是,它抛出了错误

ValueError:无法将输入数组从形状(11,10)广播到形状(11)

ValueError回溯(最近一次调用)
在()
19 w=2/((1-x)**2)*b**2)
20返回x,w
--->21正交(10)
22
正交(N,tol)
13
14而(eps>tol)和(迭代15a,b=勒让德(N,x)
16负fn=-a/b
17 x=x+负fn
在勒让德(N,x)
7打印(P.shape)
8 Q=np.零((N+1,len(x)))
---->9 P[0],P[1]=1+0*x,x
10q[0],Q[1]=0,1
11 u=P[N-1]
ValueError:无法将输入数组从形状(11,10)广播到形状(11)

哪一行导致了错误?我已经编辑了OP以包含错误
P
被初始化为2d
P[0]
然后是1d,带有
len(x)
x.shape[0]
)。但是显然
x
是2d(10,11)。您正试图将一个2d数组放入一个1d插槽。堆栈溢出上的十几个其他“无法广播”问题可能重复
ValueError                                Traceback (most recent call last)
<ipython-input-68-9f10a65c70cc> in <module>()
     19     w = 2/(((1-x)**2)*b**2)
     20     return x,w
---> 21 quadrature(10)
     22 

<ipython-input-68-9f10a65c70cc> in quadrature(N, tol)
     13 
     14     while ( eps > tol ) and (iteration < imax):
---> 15         a, b =Legendre(N,x)
     16         negfn= -a/b
     17         x = x+ negfn

<ipython-input-52-f0dbdd1f646f> in Legendre(N, x)
      7     print(P.shape)
      8     Q = np.zeros((N+1,len(x)))
----> 9     P[0], P[1] = 1 + 0*x, x
     10     Q[0], Q[1] = 0 , 1
     11     u = P[N-1]

ValueError: could not broadcast input array from shape (11,10) into shape (11)