有没有办法将长度分成几乎相等的部分,但在 Python 中将每个部分调整到最接近的 1/32?

问题描述

我设计定制橱柜,有时需要将一个运行分成 3 个橱柜,我不能让每个橱柜截面相等,因为截面宽度必须是英制的(到 1/32")并且不能有一个三分之一英寸。我通常必须做一些粗略的数学计算并根据需要调整宽度以保持运行的总长度并保持英制测量,但我正在编写一个 python 程序来为我计算这个。我承认我是Python 黑客,但我正在尽我所能。 这就是我到目前为止所拥有的 - 如何 1) 将每个部分的宽度四舍五入到最接近的 1/32" 而 2) 保持整体宽度?(即,不四舍五入到最接近的,因为它可能会抛弃整体宽度) 谢谢!

import math
# input total length of run
run_length = float(input("Enter length of the run,in inches:"))
# accounting for 1/8" reveals
reveal_num = float(input("Enter number of reveals: "))
reveal_length = reveal_num * 0.125
true_length = run_length - reveal_length
# determining number of run sections
section_num = float(input("Enter desired number of doors/sections: "))
# This is where the fun begins
# First group is nicely divisible into whole numbers
if true_length % section_num == 0:
    section_length = true_length / section_num
    print("Each section will be",section_length,"inches")
# Second group is divisible by 32nds,tested by multiplying by 32 and seeing if result is a 
whole number
# Then to be rounded to the nearest 1/32" while maintaining the total width
elif ((true_length / section_num) * 32).is_integer():
# Third group is the misfits. Must be divided to the nearest 1/32" while maintaining the total 
width.
else:

解决方法

所以有一种方法可以做到这一点,但它相当复杂。首先,您需要将您的宽度转换为第 32 位的宽度,您可以通过乘以 32 来完成。然后,为了避免重复,您需要采用剩余浮点运算的 floor。幸运的是,这是转换为整数时的默认行为,因此您可以执行以下操作来进行转换:

width32 = width * 32
width32_floor = int(width32)
new_width = float(width32_floor) / 32

需要 float 以便您拥有真正的宽度并且在除法后不会占用地板。以这种方式转换所有宽度后,您可以计算总宽度与各个宽度总和之间的差值,然后将它们均匀地(或按照您喜欢的方式)分布在各个宽度之间。