0

我想从具有不同高度和长度的数据框中分配 n 个矩形,以便总长度 (L) 和总高度 (H) 的纵横比 (r_expected) 大致为 L/H = 0.33。矩形分布逻辑示意图如下:

为了找到最佳长度,我从猜测的长度(L_guess)开始。由此我可以计算总高度(H)(注意:我省略了如何完成的详细描述,因为它是次要的)以及比率 r,如下所示:

import pandas as pd
import numpy as np

H = 0
L_guess = 18

l_cum = [2.5, 6.1, 9.9, 13.8, 18.1, 20.0] #cumulative length of rects
h = [3.5, 4.5, 6.7, 4.8, 6.8, 3.1] # height of rects
df = pd.DataFrame(list(zip(l_cum,h)), columns = ["l_cum", "h"])

tolerance = 0.01 #error tolerance for calculated ratio
r_expected = 0.33 #expected target ratio L/H


rowlist = [np.floor(i/L_guess) for i in df["l_cum"]] #check how many rects fit in L_guess by assigning a row index

for k in range(int(max(rowlist))): #check with rect has the largest height
        vals = [j for j,i in enumerate(rowlist) if i == k]
        H += max(df['h'][vals]) #add largest height to get total height

r = L_guess/H #calculated ratio out of L_guess and calculated h 

然后,如果计算的比率 r 不在预期比率 0.33 的给定容差范围内,我会更新 L_guess。现在这是我的问题:目前,我任意增加或减少 L_guess 15%,直到计算出的比率在给定的容差范围内并返回 L_guess:

if abs(r_expected - r) <= tolerance: #if ratio difference is <= tolerance
     return L_guess #stop iterating and return length that works best

elif r < r_expected: #if L_guess too small
    L_guess += L_guess * 0.15 #increase
    findbestL(df,L_guess) #try again

else: #If L_guess too big
     L_guess -= L_guess * 0.15 #decrease
     findbestL(df,L_guess)

有没有办法在不猜测的情况下找到合适的增量,从而加快计算时间?我已经阅读了旨在最小化某些看起来有些相似的函数的梯度下降?

4

0 回答 0