我总是被告知永远不要代表钱double或float类型,这次我向你提出问题:为什么?
我确信有一个很好的理由,我根本不知道它是什么.
我有一个相当粗略的代码,必须或多或少随机生成一堆百分比,存储为十进制浮点数.也就是说,它决定材料一个占总数的13.307%,然后将其存储在dict中为0.13307.
麻烦的是,我永远无法将这些数字加起来只有一个.老实说,我不完全确定问题是什么.这可能与浮子的性质有关.
这是令人讨厌的代码,在其所有过于复杂的荣耀中:
while not sum(atmosphere.values())>=1:
#Choose a material randomly
themat=random.choice(list(materials.values()))
#If the randomly chosen material is gaseous at our predicted temperature...
if themat.vapor < temp:
#Choose a random percentage that it will make up of our planet's atmosphere, then put it in the atmos dict.
atmosphere[themat]=round(random.uniform(0.001,0.5),5)
#Find out if the fractions add up to more than 1
difference=(sum(atmosphere.values())-1)
#If one does...
while difference > 0:
#Choose a random constituent
themat=random.choice(list(atmosphere.keys()))
#If that constituent has a higher fraction value than …Run Code Online (Sandbox Code Playgroud)