如何限制列表中的位数?
这是我为化学从头开始程序编写的一小段代码。我在使 C1pos 列出小数点后正好 6 位数字时遇到问题。我尝试了几种方法,例如十进制函数,但到目前为止我没有运气。
位置是一个定义,它将采用矩阵 (1,1,1)+(1,1,1) 并给出 (2,2,2) numpy 没有安装在我的服务器上。
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(' ','')
有什么建议吗?
EG:输出需要是C1,2.123456,3.123456,4.123456 数量永远不会超过10。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
示例
输出
Example
Output
您可以使用小数类将所有数字四舍五入到小数点后 6 位。
或者如果您正在对字符串执行此操作(正如我从您的代码中怀疑的那样):
you can use the decimal class to round all your numbers to 6 decimal places.
or if you are doing this operation on a string (as i suspect from your code):