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 square root unary operation "sqrt".
15   * The class extends an abstract superclass UnaryFunction.
16   */
17  public final class Sqrt extends UnaryFunction {
18  
19  	public Sqrt(Expression arg) throws IllegalConstruction {
20  		super(arg);
21  		symbol = "sqrt";
22  	}
23  
24  	@Override
25  	public Real op(Real r) {
26  		if (r.isNan() || r.isMinusInf() || r.getValue().doubleValue() < 0) {
27  			throw new IllegalArgumentException("Square root of negative number");
28  		}
29  		if (r.isPlusInf()) {
30  			return Real.plusInf();
31  		}
32  		BigDecimal val = BigDecimalMath.sqrt(r.getValue(), Real.context);
33  		return new Real(val);
34  	}
35  
36  	@Override
37  	public IntegerAtom op(IntegerAtom i) {
38  		if (i.getValue() < 0) {
39  			throw new IllegalArgumentException("Square root of negative number");
40  		}
41  		double sqrtVal = Math.sqrt(i.getValue());
42  		return new IntegerAtom((int) Math.round(sqrtVal));
43  	}
44  
45  	@Override
46  	public Complex op(Complex c) {
47  		org.apache.commons.numbers.complex.Complex val = c.getValue().sqrt();
48  		return new Complex(val);
49  	}
50  
51  	@Override
52  	public Rationnal op(Rationnal q) {
53  		if (q.getValue().doubleValue() < 0) {
54  			throw new IllegalArgumentException("Square root of negative number");
55  		}
56  		double sqrtVal = Math.sqrt(q.getValue().doubleValue());
57  		org.apache.commons.numbers.fraction.Fraction result = org.apache.commons.numbers.fraction.Fraction
58  				.from(sqrtVal);
59  		return new Rationnal(result);
60  	}
61  }