I have a piece of code that has creates a dictionary Enzyme_dict
and then fills that dictionary with objects (from class Enzyme
). One of the attributes of that class of objects is itself a dictionary (self._specif
). The dictionary that makes up that attribute is filled up with several values, all equal to 1.0/5
. Because of machine precision, this value gets printed as 0.20000000000000001
, which makes printing a dictionary with many of these values unreadable.
I want to be able to write print Enzyme_dict
and have it print all of the machine-rounded floating point values as .200
or something, instead of the unwieldy 0.20000000000000001
. How can I do this?
When I try to format the __repr__
output within the class itself with %.3f
, it tells me I can't do that because I'm trying to format a dictionary as a float (which makes sense). I would also like to keep those values that I'm trying to truncate as floats, and not turn them into strings.
I'm running python 2.6.6. Thank you for the help!
import random
random.seed(5)
numb_unique_chem = 10
numb_rxns = 10
numb_sub = 2
numb_prod = 2
E_pool_size_initial = 3
numb_rxns_cat_initial = 5
class Enzyme(object):
def __init__(self,rxns_cat,specif):
self._rxns_cat = rxns_cat
self._specif = specif
def __repr__(self):
return "Rxns catalyzed: %s, Specificity: %s \n" %(self._rxns_cat, self._specif)
Enzyme_dict = {}
R_pool_size = 10 # Rxn pool size, dictated by the input above
for ID in range(E_pool_size_initial):
Enzyme_dict[ID] = Enzyme([],{})
Enzyme_dict[ID]._rxns_cat = random.sample([n for n in range(10)],numb_rxns_cat_initial)
Enzyme_dict[ID]._specif = {}
for i in Enzyme_dict[ID]._rxns_cat:
Enzyme_dict[ID]._specif[i] = (1.0/len(Enzyme_dict[ID]._rxns_cat))
print Enzyme_dict