View Javadoc
1   package calculator.functions;
2   
3   import java.math.BigDecimal;
4   
5   import calculator.Expression;
6   import calculator.IllegalConstruction;
7   import calculator.atoms.Complex;
8   import calculator.atoms.IntegerAtom;
9   import calculator.atoms.Rationnal;
10  import calculator.atoms.Real;
11  import ch.obermuhlner.math.big.BigDecimalMath;
12  
13  /**
14   * This class represents the arithmetic unary operation "tanh".
15   * The class extends an abstract superclass UnaryOperation.
16   */
17  public final class Tanh extends UnaryFunction {
18  
19  	/**
20  	 * Class constructor specifying an Expression to apply the hyperbolic tangent
21  	 * function.
22  	 *
23  	 * @param arg The Expression to apply the operation on
24  	 * @throws IllegalConstruction If a null argument is passed
25  	 */
26  	public Tanh(Expression arg) throws IllegalConstruction {
27  		super(arg);
28  		symbol = "tanh";
29  	}
30  
31  	@Override
32  	public Real op(Real r) {
33  		if (r.isNan() || r.isMinusInf() || r.isPlusInf()) {
34  			return Real.nan();
35  		}
36  		BigDecimal val = BigDecimalMath.tanh(r.getValue(), Real.context);
37  		return new Real(val);
38  	}
39  
40  	@Override
41  	public IntegerAtom op(IntegerAtom i) {
42  		double tanVal = Math.tanh(i.getValue());
43  		return new IntegerAtom((int) Math.round(tanVal));
44  	}
45  
46  	@Override
47  	public Complex op(Complex c) {
48  		org.apache.commons.numbers.complex.Complex val = c.getValue().tanh();
49  		return new Complex(val);
50  	}
51  
52  	@Override
53  	public Rationnal op(Rationnal q) {
54  		double tanVal = Math.tanh(q.getValue().doubleValue());
55  		org.apache.commons.numbers.fraction.Fraction result = org.apache.commons.numbers.fraction.Fraction.from(tanVal);
56  		return new Rationnal(result);
57  	}
58  }