看板 Python 關於我們 聯絡資訊
# 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://www.ptt.cc/bbs/Python/M.1523693794.A.A6D.html
AlaRduTP: 把 f 的 n / 2 改成整數除法 n // 2 試試看。如果還是 04/14 17:07
AlaRduTP: 不知道差別,就把 type(200 / 2) 印出來看看吧! 04/14 17:07
znmkhxrw: 知道了!! 謝謝 04/14 18:06
Zundel: 個人認為是 function 的底層會自動幫你加上 float()(避免 04/15 10:41
Zundel: 一邊 float 一邊 int 無法運算),而你直接除的時候因為 04/15 10:41
Zundel: 兩邊都是整數所以不用加上 float 04/15 10:41
znmkhxrw: 我去檢查時確實是 fact(200)*fact(100.0)出錯 04/15 17:29
znmkhxrw: 若是fact(200)*fact(100)就不會 04/15 17:29
FakeGPS: 何不試試 math.factorial(x) 04/16 08:20