【问题标题】:How to test all possible values ​for all variables to get the maximum result for the function如何测试所有变量的所有可能值以获得函数的最大结果
【发布时间】:2019-09-28 18:36:58
【问题描述】:

我有三个变量,分别称为 a、b 和 c,它们中的每一个都可以假定在一个范围内定义了不同的值。我想创建一个函数来测试每个可能的变量值,并为我提供输出“f”的最佳组合。

a = list(range(1, 10, 2))
b = list(range(5, 8, 1))
c = list(range(1, 3, 1))

def all_combinations (a, b, c):
    #something
    f = a + (b * a) - (c*(a ^ b))
    return BEST a, b, c for my f

有可能吗?最好的方法是什么?

【问题讨论】:

  • 知道你的意思是“最好”,但这听起来像是一个优化问题
  • 是的,我就是这个意思

标签: python function combinations


【解决方案1】:

您可以使用itertools.product() 获取a、b 和c 的所有可能组合。

然后为a b c 的每个唯一组合计算您的公式,跟踪结果,如果结果比之前最好的,保存a b c 的当前值。

import itertools

def all_combinations (alist, blist, clist):
    best_a = 0
    best_b = 0
    best_c = 0
    best_f = 0
    for a,b,c in itertools.product(alist, blist, clist):
        f = a + (b * a) - (c*(a ^ b))
        if f > best_f: # use your own definition of "better"
            best_a = a
            best_b = b
            best_c = c
            best_f = f
    return best_a, best_b, best_c

【讨论】:

    【解决方案2】:

    首先,你说的是I have three variables called a, b and c, each of these can assume a different value defined in a range。请注意,代码中的变量实际上等于三个整数列表,不是三个整数。

    测试所有可能组合的简单算法是 3 个嵌套的 for 循环。在这里,我假设“最佳”是指“最大值”:

    def all_combinations (list1, list2, list3):
        best_f, best_a, best_b, best_c = None, None, None, None
    
        for a in list1:
            for b in list2:
                for c in list3:
                    f = a + (b * a) - (c*(a ^ b))
                    # here you have to define what f being "better" than best_f means:
                    if not f or f > best_f:
                        best_f = f
                        best_a = a
                        best_b = b
                        best_c = c
        return best_a, best_b, best_c
    

    【讨论】:

      【解决方案3】:

      如果您确定这些是您想要测试的唯一值,那么以下将起作用。否则你可能想看看scipy.optimize

      from itertools import product
      import numpy as np
      
      parameters = list(product(a, b, c))
      results = [my_fun(*x) for x in parameters]
      print(parameters[np.argmax(results)])
      

      如果你想最小化函数,显然将np.argmax替换为np.argmin

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-11-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-06-09
        • 2016-02-25
        • 2018-03-31
        • 1970-01-01
        相关资源
        最近更新 更多