How do I limit the number of digits in a list?
This is a small piece of code that I am writing for an chemistry ab initio program. I am having issues making the C1pos list a number with exactly 6 digits after the decimal place. I have tried several methods such as the decimal function, but so far I am having no luck.
Position is a definition that will take a matrix (1,1,1)+(1,1,1) and give you (2,2,2) numpy is not installed on my server.
class Position:
def __init__(self, data):
self.data = data
def __repr开发者_开发百科__(self):
return repr(self.data)
def __add__(self, other):
data = [] #start with an empty list
for j in range(len(self.data)):
data.append(self.data[j] + other.data[j])
return Position(data)
deltaa=2.000001
#Set number of steps +1
numx=2
numy=1
numz=1
Carbon=[1.070000,0.000000,0.000000]
startpos=[1.000000,1.000000,1.000000]
l=[]
top=os.getcwd()
lgeom=[]
for i in range(numx):
for j in range(numy):
for h in range(numz):
l=i, j, h
shift=list(l)
shiftdist=[ k*deltaa for k in shift]
C1pos=Position(Carbon)+Position(shiftdist)+Position(startpos)
ltempl[10]=' C1,'+str(C1pos).strip('[]').replace(' ','')
Any suggestions?
EG: The output needs to be C1,2.123456,3.123456,4.123456 The number will never surpass 10.
','.join("%.6f" % f for f in C1pos)
Example
C1pos = [2.123, 300.123456, 4.123456789]
print ','.join("%.6f" % f for f in C1pos)
Output
2.123000,300.123456,4.123457
you can use the decimal class to round all your numbers to 6 decimal places.
from decimal import Decimal, ROUND_UP
Decimal(n).quantize(Decimal('.000001'), rounding=ROUND_UP)
or if you are doing this operation on a string (as i suspect from your code):
print ('C1,' + ','.join(["%.6f" %x for x in C1pos]))
精彩评论