[英]Question about a Python Project about Legendre Polynomials and Gram matrices
我的問題是關於一個小型 Python 項目(數字,學習數學)。
我確信 Gram 矩陣和基應該被正確地算法化。 它在monome基礎上工作得很好,但給出了一個我不明白的其他兩個錯誤......
錯誤是模塊對象不可調用:在 for 循環的 prelambdalegendre 函數中
import math
from scipy import integrate as int
import numpy as np
def gaussklammer(n):
if n%2==0:
return n
elif n%2==1:
return n-1
monom= lambda x,n: x**n
def prelambdalegendre(x,k):
pol=0
for i in range (0,int(gaussklammer(k)/2)+1):
pol+= (-1)**i *math.factorial(2*k-2*i)/(math.factorial(k-i)*math.factorial(k-2*i)*math.factorial(i)*2**k)*(x**(k-2*i))
return pol
legendre = lambda x,n:prelambdalegendre(x,n)
normlegendre =lambda x,k: math.factorial(2*k)/(2**k *math.factorial(k)**2) *legendre(x,k)
def grammatrix(baseofchoice,size):
if baseofchoice=='monom':
base =lambda x,k:monom(x,k)
elif baseofchoice=='legendre':
base =lambda x,k:legendre(x,k)
elif baseofchoice=='normlegendre':
base =lambda x,k:normlegendre(x,k)
#More elegant implementations didn't work , unfortunately.
#To add another base, just add another elif statement
A=np.zeros((size,size))
for i in range (0,size):
for j in range (0,size):
f= lambda x : base(x,i)*base(x,j)
A[i][j]=(int.quad(f,-1,1)[0])
return A
print(grammatrix('monom',5))
print(grammatrix('legendre',5))
你的問題是你將scipy.integrate
聲明為int
,
然后在 for 循環中從 python 調用 int eger函數。
導入integrate
,請嘗試使用其他名稱導入它。
找到了另一種方法來做到這一點,無論如何感謝您的投入;)
import math
from scipy import integrate
import numpy as np
monom= lambda x,n: x**n
def legendre(x,k):
if k==0:
return 1
elif k==1:
return x
else :
pol=x*legendre(x,k-1)-((k-1)**2)/(4*(k-1)**2 -1)*legendre(x,k-2)
return pol
normlegendre =lambda x,k: math.factorial(2*k)/(2**k *math.factorial(k)**2) *legendre(x,k)
def grammatrix(baseofchoice,size):
if baseofchoice=='monom':
base =lambda x,k:monom(x,k)
elif baseofchoice=='legendre':
base=lambda x,k:legendre(x,k)
elif baseofchoice=='normlegendre':
base=lambda x,k:normlegendre(x,k)
#Dieser Liste können nach Bedarf für neue Basen neue gleichförmige Clauses
#hinzugefügt werden, elegantere Implementierungen scheiterten leider.
A=np.zeros((size,size))
for i in range (0,size):
for j in range (0,size):
f= lambda x : base(x,i)*base(x,j)
A[i][j]=(integrate.quad(f,-1,1)[0])
return A
A=grammatrix('monom',4)
print(A)
B=grammatrix('legendre',4)
print(B)
C=grammatrix('normlegendre',4)
print(C)
condA=np.linalg.cond(A)
condB=np.linalg.cond(B)
condC=np.linalg.cond(C)
print(condA)
print(condB)
print(condC)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.