View Javadoc
1   package calculator.operations;
2   
3   import java.util.List;
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  
12  /**
13   * This class represents the arithmetic sum operation "+".
14   * The class extends an abstract superclass Operation.
15   * Other subclasses of Operation represent other arithmetic operations.
16   * 
17   * @see Operation
18   * @see Minus
19   * @see Times
20   * @see Divides
21   */
22  public final class Plus extends Operation {
23  
24  	/**
25  	 * Class constructor specifying a number of Expressions to add.
26  	 *
27  	 * @param elist The list of Expressions to add
28  	 * @throws IllegalConstruction If an empty list of expressions if passed as
29  	 *                             parameter
30  	 * @see #Plus(List<Expression>)
31  	 */
32  	public Plus(List<Expression> elist) throws IllegalConstruction {
33  		super(elist);
34  		symbol = "+";
35  		neutral = 0;
36  	}
37  
38  	/**
39  	 * The actual computation of the (binary) arithmetic addition of two Reals
40  	 * 
41  	 * @param r1 The first Real
42  	 * @param r2 The second Real
43  	 * @return The (new) Real that is the result of the addition
44  	 */
45  	public Real op(Real r1, Real r2) {
46  		if ((r1.isPlusInf() && r2.isMinusInf())
47  				|| (r1.isMinusInf() && r2.isPlusInf())
48  				|| r1.isNan() || r2.isNan()) {
49  			return Real.nan(); // inf-inf = NaN or NaN +x = NaN
50  		}
51  		if (r1.isMinusInf() || r2.isMinusInf()) { // x - inf = -inf
52  			return Real.minusInf();
53  		}
54  		if (r1.isPlusInf() || r2.isPlusInf()) { // x + inf = +inf
55  			return Real.plusInf();
56  		}
57  
58  		return new Real(r1.getValue().add(r2.getValue()));
59  	}
60  
61  	/**
62  	 * The actual computation of the (binary) arithmetic addition of two Integers
63  	 * 
64  	 * @param i1 The first IntegerAtom
65  	 * @param i2 The second IntegerAtom
66  	 * @return The (new) IntegerAtom that is the result of the addition
67  	 */
68  	public IntegerAtom op(IntegerAtom i1, IntegerAtom i2) {
69  		return new IntegerAtom(i1.getValue() + i2.getValue());
70  	}
71  
72  	@Override
73  	public Complex op(Complex c1, Complex c2) {
74  		if (c1.isNaN() || c2.isNaN()) {
75  			return Complex.nan();
76  		}
77  		org.apache.commons.numbers.complex.Complex result = c1.getValue().add(c2.getValue());
78  		return new Complex(result);
79  	}
80  
81  	@Override
82  	public Rationnal op(Rationnal q1, Rationnal q2) {
83  		org.apache.commons.numbers.fraction.Fraction result = q1.getValue().add(q2.getValue());
84  		return new Rationnal(result);
85  	}
86  }