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 double
s?
A symbolic variable is a string of characters that you define as a symbol. Because the variable is a symbol, you can assign different values to it at different times. By assigning different values, you can do the same processing with different data.
In a symbol equation, substances are written using their chemical symbol or formula. The formulae of the reactants always go first in a symbol equation. The reactants are separated using a + symbol. After the reactants, there is an arrow → to show that the chemical reaction has taken place.
Suppose you have a symbolic expression f which includes the symbol x and you wish to substitute for x another symbol c or a numerical value x0. Then you can use the general subs command g=subs(f,old,new) which in our cases would be g=subs(f,x,c) or g=subs(f,x,x0).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With