Search code examples
javamathapache-commons-math

Calculating Log and Exp of a value using Apache Commons


I have a mortality risk calculation that requires the determination of natural logs and exp decay. The method is detailed below. I am curious to know why the methods for calculating exp etc are not static and if I use a single Log (or Exp) object for multiple arguments if there is a risk of incorrect calculations. That is can I use a single instance of Log to calculate Log (2.3) and Log (567)?

public Double getROD(Integer score) {

        Double beta0 = new Double(-7.7631);
        Double beta1 = new Double(0.0737);
        Double beta2 = new Double(0.9971);

        Log log = new Log();
        Exp exp = new Exp();

        Double logit = beta0 + (beta1 * score) + (beta2 * log.value(new Double(score + 1)));
        Double mortality = exp.value(logit) / (1 + exp.value(logit));

        return mortality;
    }

I have tried the following:

Log log = new Log();

Double arg1 = log.value(new Double(12.3));
Double arg2 = log.value(new Double(29.12));

System.out.println(arg1.toString() + " : " + arg2.toString());

which results in

2.509599262378372 : 3.3714252233284854

However, there is still a question as to this being the intended behaviour across all uses.


Solution

  • The Exp, Log, etc. classes store no state. The reason their value methods are not static is to fulfil the UnivariateFunction interface. So, yes, you can safely reuse the objects.

    One of the nice things about the UnivariateFunction interface is that you can write a function that takes such an object, and the user can parameterise your function by passing in an appropriate function object. This concept is called higher-order functions (if you come from the FP camp, as I do) or strategy pattern (if you come from the OOP camp).