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

时间:2018-05-31 06:36:33

标签: 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-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

但是,它会抛出错误

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

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)

0 个答案:

没有答案