python - 不明白为什么这段代码在不同版本的Python中给出不同的结果

标签 python

前段时间我发现了这个计算 pi 数字的代码:

def pi_digits():
    """generator for digits of pi"""
    q,r,t,k,n,l = 1,0,1,1,3,3
    while True:
        if 4*q+r-t < n*t:
            yield n
            q,r,t,k,n,l = (10*q,10*(r-n*t),t,k,(10*(3*q+r))/t-10*n,l)
        else:
            q,r,t,k,n,l = (q*k,(2*q+r)*l,t*l,k+1,(q*(7*k+2)+r*l)/(t*l),l+2)
digits = pi_digits()
for i in range(30): print digits.next()

现在我想在 Python 3.4 中使用它,我做了一些改变:

def pi():
    '''Generator for digits of pi'''
    q,r,t,k,n,l = 1,0,1,1,3,3
    while True:
        if 4*q+r-t < n*t:
            yield n
            q,r,t,k,n,l = (10*q,10*(r-n*t),t,k,(10*(3*q+r))/t-10*n,l)
        else:
            q,r,t,k,n,l = (q*k,(2*q+r)*l,t*l,k+1,(q*(7*k+2)+r*l)/(t*l),l+2)

def main():
    a=pi()
    i=30
    while i>0:
        print(next(a))
        i-=1

if __name__ == '__main__':
    main()

但是我的代码打印了错误的结果,例如:

3.0,
1.0476190476190477,
3.272283272283272,
3.6476767126921925,
4.078229842128079,
4.6365352277262,
5.345159217838377,
6.228740292622248,
7.819098709270982,
4.255764551767985,
5.069552326563916,
6.0642804719748575...

那么什么有区别呢?

最佳答案

我相信差异在于你的部门。在 Python 2 中,一个整数除以另一个整数会生成一个整数。在 Python 3 中,它生成一个 float 。我相信您可以使用 // 运算符代替 / 在 Python 3 中实现所需的行为。

关于python - 不明白为什么这段代码在不同版本的Python中给出不同的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33515245/

相关文章:

python - 属性错误 : 'function' object has no attribute 'upper'

python - 如何计算多项式线性回归中的误差?

python - 将 html 写入 csv 时出现奇怪的格式

python - 使用 Python 更改的墙纸在重启时重置为默认值

python 子表达式的条件覆盖

python - 使用自动完成、python 模式和绳索设置 emacs

python - 如何使用 urllib2 将经过身份验证的代理异常应用于开启器?

python - 如何向矩阵添加元素?

python - 我应该如何使用 h5py 库来存储时间序列数据?

python - SQL:使用现有表/df 中的信息创建新表/df