一段代码的Python解释

标签 python

def compose(f, g):
    return lambda x:f(g(x))

def thrice(f):
    return compose(f, compose(f, f))

def repeated(f, n):
    if n == 0:
        return identity
    else:
        return compose(f, repeated(f, n - 1))

def sq(x): return x**2

1) 打印(三次(三次)(sq)(1))

2) 打印(三次(三次(sq)(2))

谁能向我解释为什么第一个函数返回 1 而第二个函数不起作用? 我在想 thrice(thrice)(sq) 会给我 sq∘sq∘..... 27 次,所以 sq(1) 是 1^27=1,对吗? 谢谢。

最佳答案

thrice(thrice)(sq)(x) 是一个增长极快的函数:

thrice(thrice)(sq)(1.0000009)
#2.890634480354213e+52
thrice(thrice)(sq)(1.000001)
#1.9497974384856317e+58

当你将它应用到 float 时,它很快就会溢出:

thrice(thrice)(sq)(1.000006)
# OverflowError: (34, 'Numerical result out of range')

已编辑(感谢@KarlKnechtel)但是,Python 实现了任意精度整数数字。当您将该函数应用于整数(例如,thrice(thrice)(sq)(2))时,解释器会计算精确答案,然后尝试打印它,有 40,403,562 位小数,需要大量时间。

关于一段代码的Python解释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46137056/

相关文章:

python - 如何抓取网站主页的其他页面

python - for循环中的if-else在python中不起作用

python - Windows 客户端和 Linux 服务器之间的通信

python - 如何在单次观察中运行 pykalman 卡尔曼滤波器? (Python)

python - 使用 np.interp 查找给定 y 的 x 值会给出错误的答案

python - 在 python 列表理解中有没有一种方法可以不重复工作

python - 无法连接两个数据帧

python - 如何使用一种格式化程序来记录文件并使用彩色格式化程序来记录终端?

python - 如何在 numpy 行上应用通用函数?

python - 查找 ProtoBuf 的 Python DESCRIPTOR 中列出的枚举