2016-12-25 21 views
-2
def fun(p,q,x=x): 
    p=p*x^0 
    q=q*x^0 
    t=diff(q) 
    u=p.degree(x)+1 
    s=p.degree(x)-t.degree(x) 
    o=s+1 
    if s<0: 
     print('The integral does not undertake in elementary functions') 
    else: 
     if s==0: 
      A=var('A0') 
     else: 
      A=var(['A%d' %n for n in range(o)]) 
      r=sum([A[i]*(x^i) for i in range(o)]) 
      h=diff(r,x)+r*diff(q,x)-p 
      l=diff(r,x)+r*diff(q,x) 
      B=([l.coefficient(x,n) for n in range(u)]) 
      C=([p.coefficient(x,n) for n in range(u)]) 
     if o==1: 
      t=solve((B[u-1]-C[u-1]==0),r) 
      r=r.subs(t) 
      print(r) 
     else: 
      z=[h.subs(x=n)==0 for n in range(u)] 
      t=solve(z,A) 
      l=len(t[0]) 
     if t[0][l-1]!=0: 
      r=r.subs(t) 
      print(r) 
     else: 
      print('The integral does not undertake in elementary functions') 

fun(x,x**2)不起作用。 如果我會嘗試fun(x**2,x)它會工作。或fun(x,x**3)在分配之前參考的局部變量'B'

File 「」, line 1, in File 「」, line 21, in dr UnboundLocalError: local variable ‘B’ referenced before assignment

有人可以修好嗎?我嘗試了我能想象的一切。

回答

1

if if s == 0 and o == 1 then B is undefined。嘗試遵循你的代碼的邏輯。

0

變量B尚未分配給第21行中引用的任何內容,這意味着B不存在。 因此,Python提出了一個錯誤,因爲它被告知使用一個不存在的值進行計算。

相關問題