【问题标题】:Is there a way to divide a length into near equal parts but adjust each part to the nearest 1/32nd in Python?有没有办法将长度分成几乎相等的部分,但在 Python 中将每个部分调整为最接近的 1/32?
【发布时间】:2021-09-29 21:56:56
【问题描述】:

我起草定制橱柜,有时需要将运行分成 3 个橱柜,我不能让每个橱柜截面相等,因为截面宽度必须是英制的(到 1/32 英寸)并且不能有三分之一英寸。我通常需要做一些粗略的数学运算并根据需要调整宽度以保持运行的总长度并保持英制测量,但我正在编写一个 python 程序来为我计算这个。我承认我是Python 的 hack,但我正在尽力而为。 这就是我到目前为止所拥有的 - 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:

【问题讨论】:

标签: python rounding integer-division


【解决方案1】:

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

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

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

【讨论】:

  • Python 3 中不需要float(...)。由于不再支持 Python 2,除非另有说明,否则您可以假设问题与 Python 3 有关。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-01
  • 2012-11-25
  • 2011-10-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多