Decimal 's should work with whatever precision you require although if you'使用 Decimal 进行大量数字运算会比使用 float 慢得多 . 但是,我假设你只是想要在不失去任何精度的情况下转换数据,所以这应该没问题 .
1
我写完了一些字符串处理代码 . 不优雅,但它的工作原理:
stuff=loadtxt(fname1,skiprows=35,dtype="f10,f10,e10,S10,i1",delimiter=',')
stuff2 = loadtxt('keylines.txt') # a list of the reference values
... # open file for writing etc
for i in range(0,len(stuff)):
bb=round(float(stuff[i][0]),3) # gets number back to correct decimal format
cc=round(float(stuff[i][1]),5) # ditto
dd=float(stuff[i][2])
ee=stuff[i][3].replace(" ","") # gets rid of extra FORTRAN spaes
ff=int(stuff[i][4])
for item in stuff2:
if bb == item:
fn.write( str(bb)+','+str("%1.5f" % cc)+','+str("%1.4e" % dd)+','+ee+','+str(ff)+'\n')
3 回答
如果您需要精确保持精度,则需要使用decimal module . 否则,issues with floating point arithmetic limitations可能会绊倒你 .
但是,您可能完全比较
float
s是否相等,但总是允许一个软糖因子,并将输出格式化为有限数量的有效数字:loadtxt
似乎采用converters
参数,如下所示:应该管用 .
Decimal
's should work with whatever precision you require although if you'使用Decimal
进行大量数字运算会比使用float
慢得多 . 但是,我假设你只是想要在不失去任何精度的情况下转换数据,所以这应该没问题 .我写完了一些字符串处理代码 . 不优雅,但它的工作原理: