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 "cos".
15   * The class extends an abstract superclass UnaryFunction.
16   */
17  public final class Cosinus extends UnaryFunction {
18  
19  	/**
20  	 * Class constructor specifying an Expression to apply the cosine function.
21  	 *
22  	 * @param arg The Expression to apply the operation on
23  	 * @throws IllegalConstruction If a null argument is passed
24  	 */
25  	public Cosinus(Expression arg) throws IllegalConstruction {
26  		super(arg);
27  		symbol = "cos";
28  	}
29  
30  	@Override
31  	public Real op(Real r) {
32  		if (r.isNan() || r.isMinusInf() || r.isPlusInf()) {
33  			return Real.nan();
34  		}
35  
36  		BigDecimal val = BigDecimalMath.cos(r.getValue(), Real.context);
37  		return new Real(val);
38  	}
39  
40  	@Override
41  	public IntegerAtom op(IntegerAtom i) {
42  		double cosVal = Math.cos(i.getValue());
43  		return new IntegerAtom((int) Math.round(cosVal)); // Throw an error instead?
44  	}
45  
46  	@Override
47  	public Complex op(Complex c) {
48  		org.apache.commons.numbers.complex.Complex val = c.getValue().cos();
49  		return new Complex(val);
50  	}
51  
52  	@Override
53  	public Rationnal op(Rationnal q) {
54  		double cosVal = Math.cos(q.getValue().doubleValue());
55  		org.apache.commons.numbers.fraction.Fraction result = org.apache.commons.numbers.fraction.Fraction.from(cosVal);
56  		return new Rationnal(result);
57  	}
58  }