Stan function similar to roots() and real() in Matlab

Hi Everyone,

is there any function in stan for finding roots of a polynomial similar to the roots() function of Matlab?

Also, is there an equivalent to real() function in Matlab for finding the real part of a complex number.

Thanks in Advance

Algebraic solver can find polynomial roots.

Stan has no complex numbers so there’s no real() either.

1 Like

@nhuurre can the algebraic solver be used to solve a single polynomial equation of 4th order?

Yes, should be possible. Note that only one (real-valued) solution is returned. If there are multiple roots (as polynomials usually have) then the returned solution it the one closest to the initial guess.

1 Like

why 1 and not 4?

btw, I am getting the following error for the following line,

r = algebra_solver(system, x_guess, p, x_r, x_i);

fourth argument to algebra solver must be data only stan

why is it throwing this error?

The data-only restriction is a bit finicky, especially if you’re calling the solver in the functions block.
x_r and x_i should be defined in the transformed data block.

1 Like

yes I am using the solver in a functions block. (will it work if used within functions block?)

If I add x_i in the transformed data block, then I’m getting an error that x_i does not exist.

Note that x_r is not giving me any problem even if this is declared within the functions block.

Inside a function x_r and x_i must be arguments with data qualifier. Something like

function(..., data real[] x_r, data int[] x_i) {
    r = algebra_solver(system, x_guess, p, x_r, x_i);

Thanks. But I just did that before your response and it worked.

I declared x_i and x_r in the transformed data block and passed it to the function as arguments (…, real[] x_r, int[] x_i)

but dunno the purpose of adding [] after real , as missing the square brackets also gives me an error