首页 > 解决方案 > Goal Seek 在 groovy 中的实现

问题描述

我正在尝试在 groovy 中实现 Excel 目标搜索功能

我已经成功地给出了正确的结果,但我确信我的代码可以在性能和准确性方面得到改进。主要是我试图找到正确的调整来解决目标寻求的方式。硬编码的增加/法令似乎不是最好的方法,但我不确定如何计算更有效。

在这个 var thisVarToBeZero 上,我通过更改计算中的调整来获得我想要为零的所有元素的属性总和

   mapWithElements={
        element1:{
        "value2":130.24,
        "value1":33700,
        "value3":50.5,
        "result":0.0},

        element2:{
            "value1":23489,
            "value2":108.24,
            "value3":62.78,
            "result":0.0},

        element3={
               "value1":140,
               "value2":57.22,
               "value3":46.65,
               "result":0.0}            
  }  

   thisVarToBeZero =  mapWithElements.each(){ key,value->
        value["result"]=value1*(((value2*adjusment)+value2)-value3)
    }.each {it->
        it.value=it.value["result"]
    }.collect() {it->it.value}.sum()


/* at this point i have the sum of the result of all elements */

def adjustment=0.0
def exit= false
def count=0

while(!exit){

    if(thisVarToBeZero> 0){

        if(thisVarToBeZero<=2000){       // this if is a threshold in case the equation can't be zero

            exit=true
        }

        adjusment-=0.00001              //  decreese the adjusment

    }else if(thisVarToBeZero< 0){

        if(thisVarToBeZero>=-2000){       // this if is a threshold in case the equation can't be zero

            exit=true
        }

        adjusment+=0.00001              // increese the adjusment

    }else{

        exit=true
    }

    if(count>=1000000){                     // Safety variable to don't go to infinity loop
        return "Solution not found"
    }
    count++
}
return adjusment

标签: javagroovy

解决方案


这个可怕的集会

   thisVarToBeZero =  mapWithElements.each(){ key,value->
        value["result"]=value1*(((value2*adjusment)+value2)-value3)
    }.each {it->
        it.value=it.value["result"]
    }.collect() {it->it.value}.sum()

可以改写为:

thisVarToBeZero = mapWithElements.values().sum{ 
  it.value1 * ( ( ( it.value2 * adjustment ) + it.value2 ) - it.value3 ) 
}

推荐阅读