Integer/Round 获取 3 个不同数字的总和时出现问题
Integer/Round problem in getting the sum of 3 different numbers
a = 1541
b = 1575
c = 1512
# I want to ratio the sum of these numbers to 128
total = a + b + c
rounded_a = round(a*128/total) # equals 43
rounded_b = round(b*128/total) # equals 44
rounded_c = round(c*128/total) # equals 42
total_of_rounded = rounded_a + rounded_b + rounded_c # equals 129 NOT 128
# I tried the floor
floor_a = math.floor(a*128/total) # equals 42
floor_b = math.floor(b*128/total) # equals 43
floor_c = math.floor(c*128/total) # equals 41
total_of_floor = floor_a + floor_b + floor_c # equals 126 NOT 128
# The exact values
# a: 42.62057044
# b: 43.56093345
# c: 41,81849611
问题是,我怎样才能达到总数128?
注意:我应该保持整数,而不是浮点数。
注 2:我可以写一个校正函数,比如将 +1 加到总计上,但它对我来说似乎不正确。
方法是这样的:
a = 1541
b = 1575
c = 1512
# I want to ratio the sum of these numbers to 128
total = a + b + c
total_of_round = round((a*128/total)+(b*128/total)+(c*128/total))
print (total_of_round)
输出:
128
一种可能:向下舍入a
和b
,然后将缺少的部分添加到c
。
a = 1541
b = 1575
c = 1512
total = a + b + c # 4628
ra = a * 128 // total
rb = b * 128 // total
rc = (c * 128 + (a * 128)%total + (b*128)%total) // total
print(ra,rb,rc)
# (42, 43, 43)
print(ra+rb+rc)
# 128
a = 1541
b = 1575
c = 1512
# I want to ratio the sum of these numbers to 128
total = a + b + c
rounded_a = round(a*128/total) # equals 43
rounded_b = round(b*128/total) # equals 44
rounded_c = round(c*128/total) # equals 42
total_of_rounded = rounded_a + rounded_b + rounded_c # equals 129 NOT 128
# I tried the floor
floor_a = math.floor(a*128/total) # equals 42
floor_b = math.floor(b*128/total) # equals 43
floor_c = math.floor(c*128/total) # equals 41
total_of_floor = floor_a + floor_b + floor_c # equals 126 NOT 128
# The exact values
# a: 42.62057044
# b: 43.56093345
# c: 41,81849611
问题是,我怎样才能达到总数128?
注意:我应该保持整数,而不是浮点数。 注 2:我可以写一个校正函数,比如将 +1 加到总计上,但它对我来说似乎不正确。
方法是这样的:
a = 1541
b = 1575
c = 1512
# I want to ratio the sum of these numbers to 128
total = a + b + c
total_of_round = round((a*128/total)+(b*128/total)+(c*128/total))
print (total_of_round)
输出:
128
一种可能:向下舍入a
和b
,然后将缺少的部分添加到c
。
a = 1541
b = 1575
c = 1512
total = a + b + c # 4628
ra = a * 128 // total
rb = b * 128 // total
rc = (c * 128 + (a * 128)%total + (b*128)%total) // total
print(ra,rb,rc)
# (42, 43, 43)
print(ra+rb+rc)
# 128