Precision issue in python
mukesh tiwari
mukeshtiwari.iiitm at gmail.com
Sat Feb 20 06:17:23 EST 2010
Hello everyone. I think it is related to the precision with double
arithmetic so i posted here.I am trying with this problem (https://
www.spoj.pl/problems/CALCULAT) and the problem say that "Note : for
all test cases whose N>=100, its K<=15." I know precision of doubles
in c is 16 digits. Could some one please help me with this precision
issue.I used stirling (http://en.wikipedia.org/wiki/
Stirling's_approximation) to calculate the first k digits of N.
Thank you.
__author__="Administrator"
__date__ ="$Feb 19, 2010 3:16:47 PM$"
import math
if __name__ == "__main__":
n=int(raw_input())
while(n>0):
n-=1
raw_input()
l=raw_input();
m=l.split(" ")
N,K,L=int(m[0]),int(m[1]),int(m[2])
fwd,bkd=1,1
s_1,s_2="",""
if(N<=200):
for i in range(1,N+1):
fwd=fwd*i;
s=str(fwd)
s_1=s[:K]
else:
d_1=(N*math.log(N)-N+0.5*math.log(2*math.pi*N)+(1/12/N)-
(1/360/pow(N,3))+(1/1260/pow(N,5))-(1/1680/pow(N,7))+(1/1188/pow(N,9))-
(691/2730/12/11/pow(N,11))+(7/6/14/13/pow(N,13)))*math.log10(math.e)
d_2=d_1-int(d_1)+K-1
fwd=pow(10,d_2)
#print fwd
fwd=int(fwd)
s_1=str(fwd)
if(N<=500):
for i in range(1,N+1):
bkd=bkd*i
bkd=bkd%pow(10,L)
if(bkd==0):
s_2="0"*L
else:
s_2=str(bkd)
else:
s_2="0"*L
print s_1+" "+s_2
More information about the Python-list
mailing list