简体   繁体   English

如何在 GEKKO (Python) 中使用 log base 2

[英]How to use log base 2 with GEKKO (Python)

I'm trying to solve an optimization problem with GEKKO using python, I'm trying to develop some mathematical function with log and sqrt and I figure out that I should use gekko operator instead of using numpy or math function.我正在尝试使用 python 解决 GEKKO 的优化问题,我正在尝试使用 log 和 sqrt 开发一些数学函数,我发现我应该使用 gekko 运算符而不是使用 numpy 或数学函数。 I wanted to know how to implement log base 2 instead of log or log10 using gekko.我想知道如何使用 gekko 实现 log base 2 而不是 log 或 log10。

gk = GEKKO()
gk.log(...) # work
gk.sqrt(...) # work
gk.log2(...) # does not work!

Error :错误

AttributeError: 'GEKKO' object has no attribute 'log2'

Instead you can change the log base using the rule:相反,您可以使用以下规则更改日志库:

log2(x) = gk.log(x)/gk.log(2)

You can't expect for it to have all of the log bases implemented.你不能指望它实现了所有的日志库。

You can create a log2 function in Gekko, especially if you need to use it multiple times throughout your model.您可以在 Gekko 中创建log2函数,尤其是当您需要在整个模型中多次使用它时。

def glog2(x):
    return gk.log(x)/np.log(2) 

Below is a complete script that demonstrates the use of the new log2 function and shows the agreement with the Numpy log2 function.下面是一个完整的脚本,演示了新的log2函数的使用,并显示了与 Numpy log2函数的一致性。

log2 Gekko 函数

from gekko import GEKKO
import numpy as np

# compare with numpy
xnp = np.logspace(-1,4,100)
ynp = np.log2(xnp)

gk = GEKKO(remote=False)
x = gk.Param(xnp)
y,z = gk.Array(gk.Var,2)

# define a new log2 function
def glog2(x):
    return gk.log(x)/np.log(2) 

gk.Equation(y==glog2(x))
gk.options.IMODE=2; gk.solve(disp=False)

import matplotlib.pyplot as plt
plt.semilogx(xnp,ynp,'b-',lw=4,label=r'$y=\log_2(x)$ Numpy')
plt.semilogx(x.value,y.value,'r--',lw=2,label=r'$y=\log_2(x)$ Gekko')
plt.legend(); plt.xlabel('x'); plt.ylabel('y'); plt.grid(); plt.show()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM