I need to solve a transcendental equation in C++ using Octave API, but the program crashes. Maybe there is a problem with indexes?
Code:
#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;
}
Compile:
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
Error:
Аварийный останов (образ памяти сброшен на диск)
which translates to “Emergency stop (memory image flushed to disk)” according to Google Translate.
I was able to solve an algebraic equation using the example of finding the roots of a polynomial, but is it possible to solve transcendental equations like in my code above?
2
Answers
Finally got to the debugger, sorry for getting to it late. Changed the code as follows:
The compilation is still the same.
Here's what the debugger came up with:
The stopping point is on the line:
I’m assuming you’re getting a segmentation error. Because you are indexing into an empty array.
In Octave,
eval
doesn’t return anything. Sooctave_value_list retval = octave::feval ("eval", octave_value (command));
is an empty list.retval[0]
doesn’t exist.Don’t use
eval
. It’s evil.But for simplicity, this is how you’d use it:
(code not tested.)