我需要使用 Octave API 求解 C++ 中的超越方程,但程序崩溃了。也许索引有问题?
代码:
#include <iostream>
#include <octave/oct.h>
#include <octave/octave.h>
#include <octave/parse.h>
#include <octave/interpreter.h>
int main() {
// Define the equation as a string
std::string equation = "(2*x-3)^(2/3) - (x-1)^(2/3)";
// Construct the Octave command to solve the equation
std::string command = "fsolve(@(x) " + equation + ", 0)";
// Parse and evaluate the Octave command
octave_value_list retval = octave::feval ("eval", octave_value (command));
// Extract the solution from the Octave output
double solution = retval(0).double_value();
// Print the solution
std::cout << "Solution: x = " << solution << std::endl;
return 0;
}
编译:
g++ -o trans trans.cpp -I/usr/include/octave-6.4.0 -I/usr/include/octave-6.4.0/octave -I/usr/include/octave-6.4.0/octave/interpreter -I/usr/include -I/usr/include/octave-6.4.0/octave -I/usr/include/octave-6.4.0/octave/octave-config.h -loctave -loctinterp -Wl,-rpath,/usr/lib/x86_64-linux-gnu/octave/6.4.0 -L/usr/lib/x86_64-linux-gnu/octave/6.4.0 -Wl,--no-as-needed -loctave -loctinterp
cc1plus: warning: /usr/include/octave-6.4.0/octave/octave-config.h: not a directory
错误:
紧急停止(内存映像重置到磁盘)
我能够使用求多项式根的示例来求解代数方程,但是是否可以像上面的代码中那样求解超越方程?
我假设您遇到了分段错误。因为您正在索引一个空数组。
eval
不返回任何内容。所以 octave_value_list retval = octave::feval ("eval", octave_value (command));
是一个空列表。 retval[0]
不存在。
不要使用
eval
。这是邪恶的。
但为了简单起见,这就是你使用它的方式:
std::string command = "res = fsolve(@(x) " + equation + ", 0)";
octave::feval("eval", octave_value(command));
octave_value_list retval = octave::feval("res");
(代码未测试。)