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