我有一段相当粗糙的代码,必须或多或少地随机生成一堆百分比,存储为十进制浮点数。也就是说,它决定材料一占总数的 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 the amount we'd need to reduce the total to 1...
if atmosphere[themat]>(sum(atmosphere.values())-1):
#Subtract that much from it.
atmosphere[themat]-=difference
#Then break the loop, since we're done and otherwise we'd go on removing bits of the atmosphere forever.
break
else:
#Otherwise, halve its percentage and reduce difference by the amount we reduced the atmosphere
oldperc=atmosphere[themat]
atmosphere[themat]=oldperc/2
difference-=oldperc/2
#Then, finally, we correct any overcorrections the previous block made.
difference=(sum(atmosphere.values())-1)
if difference < 0:
#Choose a random mat
themat=random.choice(list(atmosphere.keys()))
#Then add enough to it that the total is 1.
atmosphere[themat]+=difference
对不起,如果我错过了一些明显的东西,或者没有提供重要的信息,但我现在很累,而且我已经尝试了好几天了。