[問題] 看似等價但出錯的code求解

看板Python作者 (QQ)時間7年前 (2018/04/14 16:16), 編輯推噓2(207)
留言9則, 4人參與, 7年前最新討論串1/1
# 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

04/14 17:07, 7年前 , 1F
把 f 的 n / 2 改成整數除法 n // 2 試試看。如果還是
04/14 17:07, 1F

04/14 17:07, 7年前 , 2F
不知道差別,就把 type(200 / 2) 印出來看看吧!
04/14 17:07, 2F

04/14 18:06, 7年前 , 3F
知道了!! 謝謝
04/14 18:06, 3F

04/15 10:41, 7年前 , 4F
個人認為是 function 的底層會自動幫你加上 float()(避免
04/15 10:41, 4F

04/15 10:41, 7年前 , 5F
一邊 float 一邊 int 無法運算),而你直接除的時候因為
04/15 10:41, 5F

04/15 10:41, 7年前 , 6F
兩邊都是整數所以不用加上 float
04/15 10:41, 6F

04/15 17:29, 7年前 , 7F
我去檢查時確實是 fact(200)*fact(100.0)出錯
04/15 17:29, 7F

04/15 17:29, 7年前 , 8F
若是fact(200)*fact(100)就不會
04/15 17:29, 8F

04/16 08:20, 7年前 , 9F
何不試試 math.factorial(x)
04/16 08:20, 9F
文章代碼(AID): #1QqRZYfj (Python)
文章代碼(AID): #1QqRZYfj (Python)