How do I evaluate a Symbolic variable in SymbolicC++?
Asked Answered
B

2

8

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?

Bibliomancy answered 19/8, 2014 at 3:31 Comment(0)
L
11

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

Loathly answered 27/1, 2015 at 22:45 Comment(0)
D
0

Try:

cout << "p" << i << " = {" << double(x_sol) << ", " << double(y_sol) << "};" << endl;
Delectable answered 19/8, 2014 at 4:18 Comment(1)
It compiled but at runtime:"Attempted to cast -1/2*(25)^(1/2)-1/2 to double failed. terminate called after throwing an instance of 'SymbolicError' Aborted"Bibliomancy

© 2022 - 2024 — McMap. All rights reserved.