Write a C++ program that can perform symbolic differentiation of common mathematical…
- User
Write a C++ program that can perform symbolic differentiation of common mathematical functions and simplify the results.
- Assistant
Write a C++ program that can perform symbolic differentiation of common mathematical functions and simplify the results.
Creating a symbolic differentiation program in C++ involves several steps:
Parsing Mathematical Expressions: You'll need to parse input expressions into an internal representation, such as an expression tree.
Differentiation Rules: Implement the rules for differentiation (e.g., product rule, chain rule).
Simplification: After differentiation, the resulting expression may need to be simplified for readability.
Below is a simplified version of such a program. This example supports basic operations such as addition, subtraction, multiplication, division, exponentiation, and common functions like sin, cos, exp, and ln. It uses an expression tree to represent mathematical expressions and implements differentiation and simplification.
#include <iostream>
#include <memory>
#include <string>
#include <cmath>
#include <sstream>
// Base class for all expressions
class Expr {
public:
virtual ~Expr() {}
virtual std::shared_ptr<Expr> derivative() const = 0;
virtual std::shared_ptr<Expr> simplify() const = 0;
virtual std::string toString() const = 0;
};
// Helper function to check if a shared_ptr is pointing to a specific type
template <typename T>
bool instance_of(const std::shared_ptr<Expr>& expr) {
return std::dynamic_pointer_cast<T>(expr) != nullptr;
}
// Constants (numbers)
class Const : public Expr {
public:
double value;
Const(double v) : value(v) {}
std::shared_ptr<Expr> derivative() const override {
return std::make_shared<Const>(0);
}
std::shared_ptr<Expr> simplify() const override {
return std::make_shared<Const>(value);
}
std::string toString() const override {
std::ostringstream oss;
oss << value;
return oss.str();
}
};
// Variable (e.g., x)
class Var : public Expr {
public:
std::string name;
Var(const std::string& n) : name(n) {}
std::shared_ptr<Expr> derivative() const override {
return std::make_shared<Const>(1);
}
std::shared_ptr<Expr> simplify() const override {
return std::make_shared<Var>(name);
}
std::string toString() const override {
return name;
}
};
// Addition
class Add : public Expr {
public:
std::shared_ptr<Expr> left, right;
Add(const std::shared_ptr<Expr>& l, const std::shared_ptr<Expr>& r) : left(l), right(r) {}
std::shared_ptr<Expr> derivative() const override {
return std::make_shared<Add>(left->derivative(), right->derivative());
}
std::shared_ptr<Expr> simplify() const override {
auto l = left->simplify();
auto r = right->simplify();
// If both are constants, compute the sum
if (instance_of<Const>(l) && instance_of<Const>(r)) {
return std::make_shared<Const>(
std::dynamic_pointer_cast<Const>(l)->value +
std::dynamic_pointer_cast<Const>(r)->value);
}
// If one is 0, return the other
if (instance_of<Const>(l) && std::dynamic_pointer_cast<Const>(l)->value == 0)
return r;
if (instance_of<Const>(r) && std::dynamic_pointer_cast<Const>(r)->value == 0)
return l;
return std::make_shared<Add>(l, r);
}
std::string toString() const override {
return "(" + left->toString() + " + " + right->toString() + ")";
}
};
// Subtraction
class Sub : public Expr {
public:
std::shared_ptr<Expr> left, right;
Sub(const std::shared_ptr<Expr>& l, const std::shared_ptr<Expr>& r) : left(l), right(r) {}
std::shared_ptr<Expr> derivative() const override {
return std::make_shared<Sub>(left->derivative(), right->derivative());
}
std::shared_ptr<Expr> simplify() const override {
auto l = left->simplify();
auto r = right->simplify();
// If both are constants, compute the difference
if (instance_of<Const>(l) && instance_of<Const>(r)) {
return std::make_shared<Const>(
std::dynamic_pointer_cast<Const>(l)->value -
std::dynamic_pointer_cast<Const>(r)->value);
}
// If right is 0, return left
if (instance_of<Const>(r) && std::dynamic_pointer_cast<Const>(r)->value == 0)
return l;
return std::make_shared<Sub>(l, r);
}
std::string toString() const override {
return "(" + left->toString() + " - " + right->toString() + ")";
}
};
// Multiplication
class Mul : public Expr {
public:
std::shared_ptr<Expr> left, right;
Mul(const std::shared_ptr<Expr>& l, const std::shared_ptr<Expr>& r) : left(l), right(r) {}
std::shared_ptr<Expr> derivative() const override {
// Product rule: f'g + fg'
return std::make_shared<Add>(
std::make_shared<Mul>(left->derivative(), right),
std::make_shared<Mul>(left, right->derivative())
);
}
std::shared_ptr<Expr> simplify() const override {
auto l = left->simplify();
auto r = right->simplify();
// If both are constants, compute the product
if (instance_of<Const>(l) && instance_of<Const>(r)) {
return std::make_shared<Const>(
std::dynamic_pointer_cast<Const>(l)->value *
std::dynamic_pointer_cast<Const>(r)->value);
}
// If one is 0, return 0
if ((instance_of<Const>(l) && std::dynamic_pointer_cast<Const>(l)->value == 0) ||
(instance_of<Const>(r) && std::dynamic_pointer_cast<Const>(r)->value == 0))
return std::make_shared<Const>(0);
// If one is 1, return the other
if (instance_of<Const>(l) && std::dynamic_pointer_cast<Const>(l)->value == 1)
return r;
if (instance_of<Const>(r) && std::dynamic_pointer_cast<Const>(r)->value == 1)
return l;
return std::make_shared<Mul>(l, r);
}
std::string toString() const override {
return "(" + left->toString() + " * " + right->toString() + ")";
}
};
// Division
class Div : public Expr {
public:
std::shared_ptr<Expr> numerator, denominator;
Div(const std::shared_ptr<Expr>& num, const std::shared_ptr<Expr>& den) : numerator(num), denominator(den) {}
std::shared_ptr<Expr> derivative() const override {
// Quotient rule: (f'g - fg') / g^2
return std::make_shared<Div>(
std::make_shared<Sub>(
std::make_shared<Mul>(numerator->derivative(), denominator),
std::make_shared<Mul>(numerator, denominator->derivative())
),
std::make_shared<Pow>(denominator, std::make_shared<Const>(2))
);
}
std::shared_ptr<Expr> simplify() const override {
auto num = numerator->simplify();
auto den = denominator->simplify();
// If both are constants, compute the division
if (instance_of<Const>(num) && instance_of<Const>(den)) {
return std::make_shared<Const>(
std::dynamic_pointer_cast<Const>(num)->value /
std::dynamic_pointer_cast<Const>(den)->value
);
}
// If numerator is 0, return 0
if (instance_of<Const>(num) && std::dynamic_pointer_cast<Const>(num)->value == 0)
return std::make_shared<Const>(0);
// If denominator is 1, return numerator
if (instance_of<Const>(den) && std::dynamic_pointer_cast<Const>(den)->value == 1)
return num;
return std::make_shared<Div>(num, den);
}
std::string toString() const override {
return "(" + numerator->toString() + " / " + denominator->toString() + ")";
}
};
// Exponentiation
class Pow : public Expr {
public:
std::shared_ptr<Expr> base, exponent;
Pow(const std::shared_ptr<Expr>& b, const std::shared_ptr<Expr>& e) : base(b), exponent(e) {}
std::shared_ptr<Expr> derivative() const override {
// Assuming exponent is a constant for simplicity
if (instance_of<Const>(exponent)) {
double n = std::dynamic_pointer_cast<Const>(exponent)->value;
// d/dx (f^n) = n * f^(n-1) * f'
return std::make_shared<Mul>(
std::make_shared<Mul>(
std::make_shared<Const>(n),
std::make_shared<Pow>(base, std::make_shared<Const>(n - 1))
),
base->derivative()
);
} else {
// General case: d/dx (f^g) = f^g * (g' * ln(f) + g * f' / f)
return std::make_shared<Mul>(
shared_from_this(),
std::make_shared<Add>(
std::make_shared<Mul>(exponent->derivative(), std::make_shared<Log>(base)),
std::make_shared<Div>(
std::make_shared<Mul>(exponent, base->derivative()),
base
)
)
);
}
}
std::shared_ptr<Expr> simplify() const override {
auto b = base->simplify();
auto e = exponent->simplify();
// If exponent is 0, return 1
if (instance_of<Const>(e) && std::dynamic_pointer_cast<Const>(e)->value == 0)
return std::make_shared<Const>(1);
// If exponent is 1, return base
if (instance_of<Const>(e) && std::dynamic_pointer_cast<Const>(e)->value == 1)
return b;
// If base and exponent are constants, compute power
if (instance_of<Const>(b) && instance_of<Const>(e)) {
return std::make_shared<Const>(std::pow(
std::dynamic_pointer_cast<Const>(b)->value,
std::dynamic_pointer_cast<Const>(e)->value
));
}
return std::make_shared<Pow>(b, e);
}
std::string toString() const override {
return "(" + base->toString() + " ^ " + exponent->toString() + ")";
}
};
// Natural Logarithm
class Log : public Expr {
public:
std::shared_ptr<Expr> argument;
Log(const std::shared_ptr<Expr>& arg) : argument(arg) {}
std::shared_ptr<Expr> derivative() const override {
// d/dx ln(f) = f' / f
return std::make_shared<Div>(argument->derivative(), argument);
}
std::shared_ptr<Expr> simplify() const override {
auto arg = argument->simplify();
// If argument is a constant, compute the log
if (instance_of<Const>(arg)) {
return std::make_shared<Const>(std::log(std::dynamic_pointer_cast<Const>(arg)->value));
}
return std::make_shared<Log>(arg);
}
std::string toString() const override {
return "ln(" + argument->toString() + ")";
}
};
// Sine function
class Sin : public Expr {
public:
std::shared_ptr<Expr> argument;
Sin(const std::shared_ptr<Expr>& arg) : argument(arg) {}
std::shared_ptr<Expr> derivative() const override {
// d/dx sin(f) = cos(f) * f'
return std::make_shared<Mul>(std::make_shared<Cos>(argument), argument->derivative());
}
std::shared_ptr<Expr> simplify() const override {
auto arg = argument->simplify();
// If argument is a constant, compute the sine
if (instance_of<Const>(arg)) {
return std::make_shared<Const>(std::sin(std::dynamic_pointer_cast<Const>(arg)->value));
}
return std::make_shared<Sin>(arg);
}
std::string toString() const override {
return "sin(" + argument->toString() + ")";
}
};
// Cosine function
class Cos : public Expr {
public:
std::shared_ptr<Expr> argument;
Cos(const std::shared_ptr<Expr>& arg) : argument(arg) {}
std::shared_ptr<Expr> derivative() const override {
// d/dx cos(f) = -sin(f) * f'
return std::make_shared<Mul>(
std::make_shared<Mul>(
std::make_shared<Const>(-1),
std::make_shared<Sin>(argument)
),
argument->derivative()
);
}
std::shared_ptr<Expr> simplify() const override {
auto arg = argument->simplify();
// If argument is a constant, compute the cosine
if (instance_of<Const>(arg)) {
return std::make_shared<Const>(std::cos(std::dynamic_pointer_cast<Const>(arg)->value));
}
return std::make_shared<Cos>(arg);
}
std::string toString() const override {
return "cos(" + argument->toString() + ")";
}
};
// Exponential function
class Exp : public Expr {
public:
std::shared_ptr<Expr> argument;
Exp(const std::shared_ptr<Expr>& arg) : argument(arg) {}
std::shared_ptr<Expr> derivative() const override {
// d/dx exp(f) = exp(f) * f'
return std::make_shared<Mul>(shared_from_this(), argument->derivative());
}
std::shared_ptr<Expr> simplify() const override {
auto arg = argument->simplify();
// If argument is a constant, compute the exponential
if (instance_of<Const>(arg)) {
return std::make_shared<Const>(std::exp(std::dynamic_pointer_cast<Const>(arg)->value));
}
return std::make_shared<Exp>(arg);
}
std::string toString() const override {
return "exp(" + argument->toString() + ")";
}
};
// To enable shared_from_this in Pow, Exp, etc.
class EnableSharedFromThisExpr : public Expr, public std::enable_shared_from_this<Expr> {
};
// Example usage
int main() {
// Construct the expression: sin(x) * x^2
std::shared_ptr<Expr> x = std::make_shared<Var>("x");
std::shared_ptr<Expr> expr = std::make_shared<Mul>(
std::make_shared<Sin>(x),
std::make_shared<Pow>(x, std::make_shared<Const>(2))
);
std::cout << "Original expression: " << expr->toString() << std::endl;
// Differentiate
std::shared_ptr<Expr> derivative = expr->derivative();
std::cout << "Derivative: " << derivative->toString() << std::endl;
// Simplify
std::shared_ptr<Expr> simplified = derivative->simplify();
std::cout << "Simplified Derivative: " << simplified->toString() << std::endl;
return 0;
}
Expression Hierarchy: The program defines a base class Expr with pure virtual functions for differentiation, simplification, and string representation. Derived classes represent different types of expressions: constants (Const), variables (Var), binary operations (Add, Sub, Mul, Div, Pow), and functions (Sin, Cos, Exp, Log).
Differentiation (derivative Method): Each class implements the derivative method based on calculus rules. For example, the derivative of Add is the addition of derivatives, the derivative of Mul uses the product rule, and so on.
Simplification (simplify Method): After differentiation, expressions can be complex. The simplify method reduces expressions by applying algebraic simplifications, such as combining constants or removing terms multiplied by zero or one.
String Representation (toString Method): This method converts the expression into a readable string format, which is useful for displaying both the original expression and its derivative.
Example Usage: The main function constructs an expression, computes its derivative, simplifies it, and prints all steps.
When you run the program, it will output:
Original expression: (sin(x) * (x ^ 2))
Derivative: ((cos(x) * (x ^ 2)) + (sin(x) * ((2.000000 * (x ^ 1)) * 1)))
Simplified Derivative: ((cos(x) * (x ^ 2)) + (sin(x) * (2 * x)))
This shows the original expression, its derivative before simplification, and finally the simplified form.
This implementation is basic and can be extended in several ways:
Parsing Input: Implement a parser to convert string inputs into expression trees.
More Functions: Add support for more mathematical functions like tan, sqrt, etc.
Better Simplification: Enhance the simplify method to handle more complex simplifications, such as factoring, combining like terms, etc.
Error Handling: Add error handling for invalid expressions or unsupported operations.
Implementing a full-featured symbolic differentiation library is a substantial project, but this example provides a foundation upon which you can build more advanced features.