作者znmkhxrw (QQ)
看板Python
标题[问题] 看似等价但出错的code求解
时间Sat Apr 14 16:16:32 2018
# fact(n):= n! = n*(n-1)*...*2*1
def fact(n):
total = 1
while n >= 1:
total *= n
n -= 1
return total
#comb(n,m):= C(n,m) = fact(n)/(fact(m)*fact(n-m))
def comb(n,m):
return fact(n)/(fact(m)*fact(n-m))
#simply define a function f as f(n):= comb(n,n/2)/2**n for even n
def f(n):
return comb(n,n/2) / 2**n
print( f(200) )
# OverflowError: int too large to convert to float
print( comb(200,100) / 2**200 )
# 0.05634..., it works!
------------------------------------------------
也就是说,上面code的f(200)跟comb(200,100) / 2**200
几乎等价
只差在有没有包成function,但是一个可以run一个却说正整数太大
除非python在定义函数是是走另外一条路??
这问题发生时觉得好奇怪完全不知道怎麽google QQ
谢谢帮忙!
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 219.68.160.241
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/Python/M.1523693794.A.A6D.html
1F:推 AlaRduTP: 把 f 的 n / 2 改成整数除法 n // 2 试试看。如果还是 04/14 17:07
2F:→ AlaRduTP: 不知道差别,就把 type(200 / 2) 印出来看看吧! 04/14 17:07
3F:→ znmkhxrw: 知道了!! 谢谢 04/14 18:06
4F:推 Zundel: 个人认为是 function 的底层会自动帮你加上 float()(避免 04/15 10:41
5F:→ Zundel: 一边 float 一边 int 无法运算),而你直接除的时候因为 04/15 10:41
6F:→ Zundel: 两边都是整数所以不用加上 float 04/15 10:41
7F:→ znmkhxrw: 我去检查时确实是 fact(200)*fact(100.0)出错 04/15 17:29
8F:→ znmkhxrw: 若是fact(200)*fact(100)就不会 04/15 17:29
9F:→ FakeGPS: 何不试试 math.factorial(x) 04/16 08:20