繁体   English   中英

关于勒让德多项式和克矩阵的 Python 项目的问题

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM