Overloaded_Operator
Overloaded_Operator

Reputation: 697

How do I evaluate a Symbolic variable in SymbolicC++?

I have been trying out a couple computer algebra libraries for C++ to use with a vector calculus course I am taking. I am having trouble with nonlinear equations in GiNaC and in SymbolicC++ it actually worked.

Here is a simple example, but the problem is I can't figure out how to evaluate to a number and maybe cast it to a double or float:

#include <iostream>
#include "symbolicc++.h"

using namespace std;
int main(void)
{
    Symbolic x("x"), y("y");

    Equation e1 = (x^2) + (y^2) == 13;
    Equation e2 = (x^2) - y == 7;

    Equations eqs = {e1, e2};
    list<Symbolic> symbs = {x, y};
    list<Equations> sols = solve(eqs, symbs);

    Symbolic x_sol, y_sol;
    int i = 1;
    for( auto iter1 = sols.begin(); iter1 != sols.end(); iter1++)
    {
        x_sol = x.subst((*(*iter1).begin()));
        y_sol = y.subst((*(--(*iter1).end())));
        cout << "p" << i << " = {" << x_sol << ", " << y_sol << "};" << endl;
        i++;
    }
    return 0;
}

With that output I can copy and past it to ginsh and it evaluates just fine, but it stays in expanded form in SymbolicC++.

The exact ouput I am getting is as follows:

p1 = {1/2*(-2*(25)^(1/2)+26)^(1/2), -1/2*(25)^(1/2)-1/2};
p2 = {1/2*(2*(25)^(1/2)+26)^(1/2), 1/2*(25)^(1/2)-1/2};
p3 = {-1/2*(-2*(25)^(1/2)+26)^(1/2), -1/2*(25)^(1/2)-1/2};
p4 = {-1/2*(2*(25)^(1/2)+26)^(1/2), 1/2*(25)^(1/2)-1/2};

How can I evaluate expressions like these and cast them to doubles?

Upvotes: 9

Views: 1672

Answers (2)

user4500715
user4500715

Reputation: 121

I realize that this an answer to almost a year old question. But there's no way to directly cast a string to a number. You would need to calculate the floating-point value you're interested - the same way you do it on a calculator. https://code.google.com/p/exprtk/ is a link to a very easy to use library to accomplish exactly what you're looking for. You will have to get the Symbolic object into a string class using a string stream

Upvotes: 12

Tom
Tom

Reputation: 7990

Try:

cout << "p" << i << " = {" << double(x_sol) << ", " << double(y_sol) << "};" << endl;

Upvotes: 0

Related Questions