Python MATPLOT LIB 2D数组

时间:2017-11-21 23:24:50

标签: python arrays matplotlib

我刚开始使用matplot lib试图绘制差异的3d表面。具体来说,我有一个编写自己的ArcTan函数的任务,在代码中看作ExtArcTan,并将其值与pythons自身的值进行比较,在代码中看作atan。我对X和N的不同值执行此操作.N指的是函数中的系列项的数量,因为它实际上是泰勒近似。

我从创建x和N数组开始:

  N=np.arange(50)
  X=np.arange(-5,6) 
  N,X=np.meshgrid(N,X)

然后我需要为这两个变量中的每一个计算给定的差分,以下代码会引发错误。

Diff=abs(ExtArcTan(X,N)-atan(X))

如果没有最终的数组,我无法完成将数组放入绘图中以生成曲面的简单任务。

我在Diff行上出现此错误:

ValueError: The truth value of an array with more than one element is 
ambiguous. Use a.any() or a.all()

不确定我做错了什么:

供参考:

def ArcTanComponent(x,i): #calculates the ith component of arctan(x) taylor series
   return (((-1)**i)/(2*i+1))*(x**(2*i+1))

def BaseArcTan(x,N): #calculates all components for given N and sums to give approximation of arctan(x)
   Components=[]
   for i in range(N+1):
       Components.append(ArcTanComponent(x,i))
   return np.sum(Components)

def ExtArcTan(x,N): #extends baseArcTan function to work over entire range
    if (x>0):
        return PI/2 - BaseArcTan(1/x,N)
    elif(x<0):
         return -PI/2 - BaseArcTan(1/x,N)
    elif(x==0):
         return 0

1 个答案:

答案 0 :(得分:-1)

ExtArcTan(x,N)中,您使用if x>0:(以及其他比较),如果x是数组,则会出现不明确的错误。然后从X发送N,X=np.meshgrid(N,X)这是一个数组。例如,您需要使用元素检查np.where,而不是使用x==0检查整个数组。

编辑:这件事(未经测试)怎么样:

def ExtArcTan(x,N):
    x = np.sum(ArcTanComponent(x,i) for i in range(N+1))
    if (x>0):
        return PI/2 - BaseArcTan(1/x,N)
    elif(x<0):
         return -PI/2 - BaseArcTan(1/x,N)
    elif(x==0):
         return 0

EAT = np.array([[ExtArcTan(x,N) for x in row] for row in X])
Diff=abs(EAT-atan(X))
相关问题