/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package jmathexpr.arithmetic.func;
import jmathexpr.Expression;
import jmathexpr.arithmetic.ANumber;
import jmathexpr.arithmetic.op.Negation;
/**
* The absolute value function f(x) = |x|.
*
* @author Elemér Furka
*/
public class Abs extends UnivariateNumberFunction {
public Abs(Expression arg) {
super("exp", arg);
}
@Override
public Expression evaluate() {
Expression x = arg.evaluate();
if (x instanceof ANumber) {
ANumber a = (ANumber) x;
if (a.isNegative()) {
return a.negate();
} else {
return a;
}
} else if (x instanceof Negation) { // |-x| = x
return ((Negation) x).getChild();
} else if (x instanceof Sqrt) { // sqrt(x) >= 0
return x;
}
return new Abs(x);
}
@Override
protected UnivariateNumberFunction create(Expression arg) {
return new Abs(arg);
}
@Override
public String toString() {
return String.format("|%s|", arg);
}
@Override
public String toUnicode() {
return toString();
}
}