python标绘RecursionError:在比较中超过了最大递归深度

时间:2019-04-27 01:34:35

标签: python python-3.x matplotlib python-3.7

我尝试运行下面的代码

import math
import random
from matplotlib import pyplot as plt
from collections import Counter

def bucketize(point,bucket_size):
    return bucket_size * math.floor(point/bucket_size)

def make_histogram(points, bucket_size):
    return Counter(bucketize(point,bucket_size) for point in points)

def plot_histogram(points,bucket_size,title=""):    
    histogram = make_histogram(points,bucket_size)
    plt.bar(histogram.keys(),histogram.values(),width=bucket_size)
    plt.title(title)
    plt.show()

def inverse_normalCDF(p,miu=0,sigma=1,tolerance=0.00001):
    if miu !=0 or sigma !=1:
        return miu + sigma * inverse_normalCDF(p,tolerance=tolerance)
    low_z,low_p = -10.0,0
    hi_z,hi_p = 10.0,1
    while hi_z - low_z > tolerance:
        mid_z = (low_z + hi_z)/2
        mid_p = normalCDF(mid_z)
        if mid_p > p:
            low_z,low_p = mid_z,mid_p
        elif mid_p > p:
            hi_z, hi_p = mid_z,mid_p
        else:
            break
    return mid_z

def normalCDF(x,miu=0,sigma=1):
    return (1+math.erf((x-miu)/math.sqrt(2)/sigma))/2


random.seed(0)
#uniform = [200*random.random()-100 for _ in range (10000)]
#plot_histogram(uniform,10,"uniform histogram")
normal = [57 * inverse_normalCDF(random.random() for _ in range(10000))]
plot_histogram(normal,10,"normal histogram")

但是程序显示错误消息“ RecursionError:比较中超过了最大递归深度”,我应该怎么做才能修复RecursionError,因为它会影响inverse_normalCDF函数?

该错误不再显示函数中已超过的最大递归深度

Traceback (most recent call last):
  File "C:\Users\asus\Documents\Sublime\dataScience\normalHistogram.py", line 41, in <module>
    normal = [57 * inverse_normalCDF(random.random() for _ in range(10000))]
  File "C:\Users\asus\Documents\Sublime\dataScience\normalHistogram.py", line 26, in inverse_normalCDF
    if mid_p > p:
TypeError: '>' not supported between instances of 'float' and 'generator'
[Finished in 0.7s]

我使用的pyhton版本是3.7,而我使用的matplotlib版本是3.0.3

*更新,更改了

  

def inverse_normalCDF(p,miu = 0,sigma = 1,tolerance = 0.00001):   修正代码中的错字

1 个答案:

答案 0 :(得分:1)

您快到了。可以通过重写列表理解来解决该错误:

class Foo {
    var s1: String?
    var s2: String?
    var s3: String?

    init(s1: String?, s2: String?, s3: String?) {
        self.s1 = s1
        self.s2 = s2
        self.s3 = s3
    }
}

let foo = Foo(s1: "Test1", s2: nil, s3: "Test3")

我只是移动了一个右括号,以便函数inverse_normalCDF每次迭代都传递一个值,而不是整个生成器。