diff options
Diffstat (limited to 'differentiator.cpp')
-rw-r--r-- | differentiator.cpp | 77 |
1 files changed, 77 insertions, 0 deletions
diff --git a/differentiator.cpp b/differentiator.cpp new file mode 100644 index 0000000..739c19a --- /dev/null +++ b/differentiator.cpp @@ -0,0 +1,77 @@ +/* PIA - Lenguajes Modernos de Programación + * FACULTAD DE CIENCIAS FÍSICO MATEMÁTICAS + * Luis Sebastián Martínez Vega - LCC */ + +#include "include/differentiator.hpp" +#include "include/expressions.hpp" + +Differentiator::Differentiator() { + differential = NULL; + ptr = NULL; +} + +// Regla del constante. f(x)=c, f'(x)=0. +Expression *Differentiator::visit(Literal *expr) { + return new Literal(0); +} + +// Regla de la variable. f(x)=x, f'(x)=1 +Expression *Differentiator::visit(Variable *expr) { + return new Literal(1); +} + +// Reglas de funciones trigonométricas. +Expression *Differentiator::visit(Function *expr) { + Expression *diff; + + switch (expr->getFunctionName()) { + case i_sin: + diff = new MultiplicationExpression(new Function(expr->getArg()->copy(), i_cos), expr->getArg()->diff(this)); + + return diff; + case i_cos: + diff = new MultiplicationExpression(new NegationExpression(new Function(expr->getArg()->copy(), i_sin)), expr->getArg()->diff(this)); + + return diff; + case i_tan: + diff = new MultiplicationExpression(new PowerExpression(new Function(expr->getArg()->copy(), i_sec), new Literal(2)), + expr->getArg()->diff(this)); + + return diff; + case i_csc: + diff = new MultiplicationExpression(new MultiplicationExpression(new NegationExpression(new Function(expr->getArg()->copy(), i_csc)), + new Function(expr->getArg()->copy(), i_ctg)), expr->getArg()->diff(this)); + + return diff; + case i_sec: + diff = new MultiplicationExpression(new MultiplicationExpression(new Function(expr->getArg()->copy(), i_sec), + new Function(expr->getArg()->copy(), i_tan)), expr->getArg()->diff(this)); + + return diff; + case i_ctg: + diff = new MultiplicationExpression(new NegationExpression(new PowerExpression(new Function(expr->getArg()->copy(), i_csc), + new Literal(2))), expr->getArg()->copy()); + + return diff; + } +} + +Expression *Differentiator::visit(NegationExpression *expr) { + return new NegationExpression(expr->diff(this)); +} + +Expression *Differentiator::visit(AddExpression *expr) { + return new AddExpression(expr->getLeft()->diff(this), expr->getRight()->diff(this)); +} + +Expression *Differentiator::visit(SubExpression *expr) { + return new SubExpression(expr->getLeft()->diff(this), expr->getRight()->diff(this)); +} + +// Regla de la potencia. f(x)=x^c, f'(x)=c*x^(c-1)}*f'(x). +Expression *Differentiator::visit(PowerExpression *expr) { + Literal *c = dynamic_cast<Literal *>(expr->getRight()); + + return new MultiplicationExpression(new MultiplicationExpression(c->copy(), new PowerExpression(expr->getLeft()->copy(), new Literal(c->getValue() - 1))), + expr->getLeft()->diff(this)); +} |