Content  


Example: Substitution

In addition to evaluation, ViennaMath also allows for a substitution of constants, variables, or sub-expressions of an expression with another expression:

Run Time Substitution
viennamath::variable x(0);
viennamath::variable y(1);
viennamath::variable z(2);
 
viennamath::expr f = x + y - z;
 
// substitute z with (1 + x) in f:
std::cout << viennamath::substitute(z, 1.0 + x, f) << std::endl; // prints x + y + 1 + x
// substitute (1+x) with (1-x) in (1+x)*(1-x)
std::cout << viennamath::substitute(1+x, 1-x, (1+x)*(1-x)) << std::endl; // prints (1-x)^2
// substitute 2.0 with 3.1415 in 2.0 * x
std::cout << viennamath::substitute(2.0, 3.1415, 2.0 * x) << std::endl; // prints 3.1415*x
 

The run time substitution above can again be carried out at compile time, again provided that the respective compile time types are used for the constants and variables:

Compile Time Substitution
viennamath::ct_variable<0> x;  // represents zeroth entry in a vector
viennamath::ct_variable<1> y;  // represents first entry in a vector
viennamath::ct_variable<2> z;  // represents second entry in a vector
viennamath::ct_constant<1> c1; // compile time representation of '1'
viennamath::ct_constant<2> c2; // compile time representation of '2'
viennamath::ct_constant<4> c4; // compile time representation of '4'
 
// substitute z with (1 + x) in x + y - z:
std::cout << viennamath::substitute(z, c1 + x, x+y-z) << std::endl; // prints x+y+1+x
// substitute (1+x) with (1-x) in (1+x)*(1-x)
std::cout << viennamath::substitute(c1+x, c1-x, (c1+x)*(c1-x)) << std::endl;
// substitute 2 with 4 in 2 * x
std::cout << viennamath::substitute(c2, c4, c2 * x) << std::endl; // prints 4*x