Does anyone know of a Linux command that reads a linear system of equations from its standard input and writes the solution (if exists) in its standard output?
I want to do something like this:
generate_system | solve_system
Does anyone know of a Linux command that reads a linear system of equations from its standard input and writes the solution (if exists) in its standard output?
I want to do something like this:
generate_system | solve_system
This is an old question, but showed up in my searches for this problem, so I'm adding an answer here.
I used maxima
's solve
function. Wrangling the input/output to/from maxima
is a bit of a challenge, but can be done.
EQs="C[1]+C[2]=1,C[1]-C[2]=2"
. I wanted a solution for an unknown number of variables, so I used C[n]
, but you can use variable names.EQ_VARS="C[1],C[2]"
[C[1]=...,C[2]=..]
. We need to resolve all of these.Taken together, this becomes
OUT_VALS=( \
$(maxima --very-quiet \
--batch-string="display2d:false\$linel:9999\$print(map(rhs,float(solve([$EQs],[$EQ_VARS]))[1]))\$" \
| tail -n 1 \
| tr -c '0-9-.e' ' ') )
which will place the solution values into the array $OUT_VALS
.
Note that this only properly handles that Maxima output if your problem is correctly constrained -- if you have zero, or more than one solution, the output will not be parsed correctly.