java - 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
解决方案
这个可怕的集会
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 )
}
推荐阅读
- csv - 如何在 spark scala 中加载包含多行记录的 CSV 文件?
- ios - 每次用户进入后台至少 30 秒时,在 iOS 13 上运行的 iOS 应用都会重置
- node.js - 如何使用 html-pdf 渲染 html 标签/生成动态表格
- python - 霍伊得到精确的逆预测结果?- sklearn 预测完全错误
- python - python如何从不在sys.path中的路径加载模块
- angular - 如何在 TypeScript 中添加 *ngIf 模板字符串
- azure-devops - Azure Pipeline 构建特定的拉取请求
- excel - Excel 工作表,其中列的数字存储为文本和整数 - 熊猫问题
- javascript - 如何在Angular中选择对象列表的不同属性值
- angular - 多个组件上的同一商店