用python模拟内核密度的问题

时间:2018-11-11 09:49:45

标签: python simulation

我想获得内核密度的模拟观察结果,但是我有以下错误类型:TypeError:+不支持的操作数类型:“ float”和“ NoneType”

如何解决? 这是我使用的代码:

    from matplotlib.pyplot import *
    from math import *
    from array import *
    import numpy as np 
    from numpy.random import *
    from scipy.misc import *
    from scipy.stats import *
    from scipy import *
    from random import *


    N=1000
    n=30
    lamb=0.5
    X=lamb*tan(pi*(np.reshape(rand(n,1),n)-0.5)) #loi de Cauchy  
    x=1
    alpha=0.45

    def k_gaussien(x):
        sigma=1
        if(sigma<=0):
            return((1/(sigma*sqrt(2*pi)))*exp(-(x**2/(2*sigma**2))))

    def h(n,alpha):
        for i in range(1,n):   
            return (i**(1-alpha))

    def f_PR(x,X,alpha):
        global F;
        F = ones((n,1))
        h_n = h(n,alpha)
        for k in range(2,n):
            for i in  range(1,k):
                F[k] = F[k-1] + k_gaussien((x-X[i])*i**alpha)
            F[k] = F[k-1] * h_n
        return F

    # Almost sure convergence f_n(x)--> f(x) ps
    figure(figsize=(20,10))
    fPR=f_PR(x,X,alpha)
    T=linspace(1,n,n);
    plot(cumsum(fPR)/T)
    plot(T,(1/pi)*(lamb/(lamb**2 + y**2))*linspace(1,1,N),"r--",lw=3)#with Cauchy density
    grid(True)
    title("convergence presque sure",fontsize=20,color="blue")

    #Convergence in mean N(0,e2f(x))
    hist(fPR,bins=linspace(-10,10,50),normed=True)
    y=linspace(-10,10,100);
    v=(1/pi)*(lamb/(lamb**2 + y**2))
    plot(y,(1/sqrt(2*pi)*v)*exp ((-(y*y)/(2*v**2)))*linspace(1,1,n),'r--') #with cauchy density
    title("convergence asymptotique", fontsize=20,color="blue")

TypeError跟踪(最近一次通话最近)

<ipython-input-76-13bc86608417> in <module>()
         38 # Almost sure convergence f_n(x)--> f(x) ps
         39 figure(figsize=(20,10))
    ---> 40 fPR=f_PR(x,X,alpha)
         41 T=linspace(1,n,n);
         42 plot(cumsum(fPR)/T)

    <ipython-input-76-13bc86608417> in f_PR(x, X, alpha)
         32     for k in range(2,n):
         33         for i in  range(1,k):
    ---> 34             F[k] = F[k-1] + k_gaussien((x-X[i])*i**alpha)
         35         F[k] = F[k-1] * h_n
         36     return F

TypeError:+不支持的操作数类型:“ float”和“ NoneType”

1 个答案:

答案 0 :(得分:0)

在您的定义中:

def k_gaussien(x):
    sigma=1
    if(sigma<=0):
        return((1/(sigma*sqrt(2*pi)))*exp(-(x**2/(2*sigma**2))))

您对sigma=1进行了硬编码,但是您的函数仅在sigma<=0时返回某些内容,而这永远不会发生。因此k_gaussien((x-X[i])*i**alpha)将返回None。因此,F[k] = F[k-1] + k_gaussien((x-X[i])*i**alpha)尝试对float和None类型求和,这是行不通的。