scipy 在python中迭代以获取低于目标值的变量

20jt8wwn  于 2022-11-10  发布在  Python
关注(0)|答案(1)|浏览(154)

我正在尝试创建一个代码,既计算两个污染物水平,又迭代其中一个输入,使它们低于各自的目标值。在计算污染物之前,有大量的代码,所以如果我共享整个代码,只会很混乱。我将尽我所能使用一些伪代码/计算片段代替。


# pseudo inputs.

a = 10.0; b = 5.0; c = 15.0
d = 0.5; e = 1.0

# pseudo outputs

contaminant_1 = a * b + c
contaminant_2 = a * d + e

# target values

contaminant_1_target = 10.0
contaminant_2_target = 2.0

我想让代码使用输入a进行迭代,以得到contaminant_1 < contaminant_1_targetcontaminant_2 < contaminant_2_target

wbrvyc0a

wbrvyc0a1#

如果要迭代以查找满足条件的值a,则需要for-循环或while-循环,并在此循环中更改值a

a = 10.0
b = 5.0
c = 15.0
d = 0.5
e = 1.0

# target values

contaminant_1_target = 10.0
contaminant_2_target = 2.0

step = -0.1  # precision

while True:
    # pseudo outputs
    contaminant_1 = a * b + c
    contaminant_2 = a * d + e
    #print(contaminant_1, contaminant_2)

    if contaminant_1 < contaminant_1_target and contaminant_2 < contaminant_2_target:
        print(a)
        break
    else:
        a += step

编辑:

但如果你使用了错误的step,那么它可能会计算在错误的方向,它将永远运行。它需要检查,如果当前值大于以前的值,并作出更正。
它看起来类似于machine learninglinear regresion,它们使用Least squares来查找匹配函数
它将(contaminant_1 - contaminant_1_target)^2与先前的值进行比较,以查看它是否必须改变方向。

编辑:

比较当前和以前的(contaminant_1 - contaminant_1_target)^2并更改step = -step的版本-它可以从低于或高于结果的a开始。
(维基百科:least squares


# - constants -  `UPPER_CASE_NAMES`

B = 5.0
C = 15.0
D = 0.5
E = 1.0

# - variables - `lower_case_names`

a = 1.0

# a = 10.0

# --------------------------------

# target values

contaminant_1_target = 10.0
contaminant_2_target = 2.0

step = -0.1  # precision

# at start it should be rather `infinity`

previous_LS_1 = 0  # least squares
previous_LS_2 = 0  # least squares

while True:
    # pseudo outputs
    contaminant_1 = a * B + C
    contaminant_2 = a * D + E
    #print(contaminant_1, contaminant_2)

    # ---

    current_LS_1 = (contaminant_1 - contaminant_1_target)**2
    current_LS_2 = (contaminant_2 - contaminant_2_target)**2

    if current_LS_1 > previous_LS_1 and current_LS_2 > previous_LS_2:
        print('change direction:', a)
        step = -step

    previous_LS_1 = current_LS_1
    previous_LS_2 = current_LS_2

    # ---

    if contaminant_1 < contaminant_1_target and contaminant_2 < contaminant_2_target:
        print('a:', a)
        break
    else:
        a += step

相关问题