python - 获得 3 个不同数字之和的整数/舍入问题
问题描述
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
,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
推荐阅读
- java - 如何在 Spring 表达式语言中处理多个后备值
- python - Django `assertNumQueries` 显示延迟字段上的重复查询
- sql - 按表现分组后加入
- c++ - 如何设置一个指针属性,以便它可以调用 EXPECT_CALL 的函数?
- azure-data-explorer - 按列分组,但用逗号分隔另一列
- layout - TabbledShowLayout 中 3 个选项卡的相同路径 - ReactAdmin
- jmeter - Jmeter - Bad request 400 received, although 200 is expected
- javascript - 我如何在 javascript 中以可调整的时间重复函数
- javascript - Express.js 应用程序错误:使用类别名称作为帖子 ID
- python - 通过列的交集选择行