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 "acos".
15   * The class extends an abstract superclass UnaryFunction.
16   */
17  public final class Arccosinus extends UnaryFunction {
18  
19  	/**
20  	 * Class constructor specifying an Expression to apply the arccosine function.
21  	 *
22  	 * @param arg The Expression to apply the operation on
23  	 * @throws IllegalConstruction If a null argument is passed
24  	 */
25  	public Arccosinus(Expression arg) throws IllegalConstruction {
26  		super(arg);
27  		symbol = "acos";
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  		if (r.getValue().compareTo(new BigDecimal(-1)) <= -1 // r < -1
37  				|| r.getValue().compareTo(new BigDecimal(1)) >= 1) // r > 1
38  			return Real.nan();
39  
40  		BigDecimal acosVal = BigDecimalMath.acos(r.getValue(), Real.context);
41  		return new Real(acosVal);
42  	}
43  
44  	@Override
45  	public IntegerAtom op(IntegerAtom i) {
46  		double acosVal = Math.acos(i.getValue());
47  		return new IntegerAtom((int) Math.round(acosVal));
48  	}
49  
50  	@Override
51  	public Complex op(Complex c) {
52  		org.apache.commons.numbers.complex.Complex val = c.getValue().acos();
53  		return new Complex(val);
54  	}
55  
56  	@Override
57  	public Rationnal op(Rationnal q) {
58  		double val = q.getValue().doubleValue();
59  		if (val < -1.0 || val > 1.0) {
60  			throw new ArithmeticException("Domain error: Arccosinus requires input in the range [-1, 1].");
61  		}
62  		double acosVal = Math.acos(val);
63  		return new Rationnal(org.apache.commons.numbers.fraction.Fraction.from(acosVal));
64  	}
65  }