LocalSolver快速入门指南(连载三十一) -- 外部函数实例 C++

外部函数C++代码实例

C++中,必须扩展LSExternalFunction类,特别是call()方法来实现外部函数(1)

然后(2),实例化函数并使用createExternalFunction()方法将其转换为一个LSExpression

最后(步骤3),可以在O_Call表达式中使用你的函数。要创建O_Call表达式,可以使用泛型方法createExpression()、快捷方法call()或在LSExpression上使用特定重载的:cpp:func:~LSExpression::operator()。外部函数的参数值将通过LSExternalArgumentValues公开。

你可以通过getExternalContext()来访问函数的LSExternalContext(外部函数上下文):

#include <cmath>
#include <localsolver.h>
...
 
 
// Step 1: implement the external function
class LSArcCos : public LSExternalFunction<lsdouble> {
    
    
public:
    lsdouble call(const LSExternalArgumentValues& argumentValues) {
    
    
        return std::acos(argumentValues.getDoubleValue(0));
    }
}
 
 
LocalSolver ls;
LSModel m = ls.getModel();
LSArcCos acosCode;
// Step 2: Turn the external code into an LSExpression
LSExpression acosFunc = m.createExternalFunction(&acosCode);
acosFunc.getExternalContext().setLowerBound(0.0);
acosFunc.getExternalContext().setUpperBound(3.15);
LSExpression x = m.floatVar(-0.5, 0.5);
LSExpression y = m.floatVar(-0.5, 0.5);
// Step 3: Call the function
m.minimize(acosFunc(x + y));
m.constraint(x + 3*y >= 0.75);
...

更多问题请致电无锡迅合信息科技有限公司LOCAL SOLVER国内独家代理商数学建模工程师。下一篇:《 Local Solver 外部函数实例 C# 》!

猜你喜欢

转载自blog.csdn.net/qq_31243247/article/details/121049819