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

作者: znmkhxrw (QQ)   2018-04-14 16:16:32
# 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!
作者: AlaRduTP (Eden)   2018-04-14 17:07:00
把 f 的 n / 2 改成整數除法 n // 2 試試看。如果還是不知道差別,就把 type(200 / 2) 印出來看看吧!
作者: znmkhxrw (QQ)   2018-04-14 18:06:00
知道了!! 謝謝
作者: Zundel (編圓人)   2018-04-15 10:41:00
個人認為是 function 的底層會自動幫你加上 float()(避免一邊 float 一邊 int 無法運算),而你直接除的時候因為兩邊都是整數所以不用加上 float
作者: znmkhxrw (QQ)   2018-04-15 17:29:00
我去檢查時確實是 fact(200)*fact(100.0)出錯若是fact(200)*fact(100)就不會
作者: FakeGPS (一次就上手)   2018-04-16 08:20:00
何不試試 math.factorial(x)

Links booklink

Contact Us: admin [ a t ] ucptt.com