代码之家  ›  专栏  ›  技术社区  ›  Myccha

可能是熊猫虫?

  •  0
  • Myccha  · 技术社区  · 4 年前

    看看Python/Pandas中的一些奇怪行为。

    我知道设置很复杂,我在做一些。。。挑战。

    def lucas_n(n):
        '''Return the fist n lucas numbers modulo 1_000_007'''
        my_list = [1,3]
        while len(my_list) < n:
            my_list.append((my_list[-1]+my_list[-2])%1_000_007)
        return my_list
    
    def f(seq):
        '''Look up https://projecteuler.net/problem=739'''
        
        df = pd.Series(seq)
        
        for i in range(len(seq)-1):
            df = df.iloc[1:].cumsum()
            
        return df.iloc[0]
    
    x = lucas_n(1e4)
    
    f(x)
    
    >>> -8402283173942682253
    
    

    简言之, x 是一个正整数序列,以及 f 连续应用 .iloc[1:].cumsum() 操作。

    输出为负。。。

    这是一个bug吗?数据类型问题?

    0 回复  |  直到 4 年前
        1
  •  3
  •   NotAName    4 年前

    您似乎有整数溢出。在Python中,整数本身可以具有任意精度,但由于panda/numpy默认使用C数据类型,因此可能会发生溢出:

    enter link description here

    为了解决这个问题,您可能需要手动将数据转换为Python整数:

    def f(seq):
        '''Look up https://projecteuler.net/problem=739'''
        
        df = pd.Series(seq).astype('int') # Casting to Python integer type
        
        for i in range(len(seq)-1):
            df = df.iloc[1:].cumsum()
            
        return df.iloc[0]
    

    这解决了我测试中的溢出问题。