python的浮點數精度
下方有python和c版本的兩種code
做的事是一樣的
但算出來 兩者在小數點後幾位卻不太一樣
而且c的才是較準確的
這是google code jam的題目 c的可以過 但python不行
題目 http://code.google.com/codejam/contest/dashboard?c=188266#s=p2
請問為什麼會這樣??
python版==================
import psyco
psyco.full()
floor=[1,1]
for i in range(2,11):
floor.append(i*floor[-1])
def C(n,m):
#print n,m
return ((floor[n]+0.0)/floor[m]/floor[n-m])
def K(t,c,r,dp):
if r in dp:
return dp[r]
sq=0.0
for i in range(1,r+1):
sq+=C(r,i)*C(t-r,c-i)/C(t,c)*(1+K(t,c,r-i,dp))
cir=C(r,0)*C(t-r,c)/C(t,c)
ret=(sq+cir)/(1-cir)
dp[r]=ret
return ret
casenu=int(raw_input())
for i in xrange(casenu):
c,n=[int(e) for e in raw_input().split()]
dp={}
dp[0]=0
print "Case #%d: %.7f" % (i+1, 1+K(c,n,c-n,dp))
c版本==============================================
#include <iostream>
using namespace std;
double floor(int x){
if (x==0) return 1;
double ret=1;
for (int i=x; i>=1; i--){
ret*=i;
}
return ret;
}
double com(int n, int m){
return ((floor(n))/floor(m)/floor(n-m));
}
double C[11][11];
double K(int t, int c, int r){
if (r==0) return 0;
double sq=0.0;
for (int i=1; i<=r; i++){
sq+=C[r][i]*(C[t-r][c-i]/C[t][c])*(1+K(t,c,r-i));
}
double cir=C[r][0]*(C[t-r][c]/C[t][c]);
double ret=(sq+cir)/(1-cir);
return ret;
}
int main(){
for (int i=0; i<11; i++){
for (int j=0; j<11; j++){
if (j>i){
C[i][j]=0;
}
else {
C[i][j]=com(i,j);
}
}
}
int casenum,c,n;
cin>>casenum;
for (int caseid=1; caseid<=casenum; caseid++){
cin>>c>>n;
printf("Case #%d: %.8f\n", caseid, 1+K(c,n,c-n));
}
return 0;
}
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 220.135.140.149
※ 編輯: Arton0306 來自: 220.135.140.149 (09/13 15:02)
→
09/13 15:05, , 1F
09/13 15:05, 1F
→
09/14 01:06, , 2F
09/14 01:06, 2F
→
09/14 03:42, , 3F
09/14 03:42, 3F
推
09/14 04:45, , 4F
09/14 04:45, 4F
→
09/14 04:45, , 5F
09/14 04:45, 5F
→
09/14 04:52, , 6F
09/14 04:52, 6F
→
09/14 05:41, , 7F
09/14 05:41, 7F
→
09/14 05:42, , 8F
09/14 05:42, 8F
→
09/14 06:17, , 9F
09/14 06:17, 9F
→
09/14 06:18, , 10F
09/14 06:18, 10F
Python 近期熱門文章
PTT數位生活區 即時熱門文章