Hi. As per an advice in a well-known book (that one should not cite): In order to compute a numerical approximation to the derivative:
f'(x) ~ [ f(x + h) - f(x) ] / h the "h" should be a number representable in the set of floating point numbers being used (e.g. "double"). It seems that a code like ---CUT--- final double delta = x + h - x; final double deriv = (f.value(x + delta) - f.value(x)) / delta; ---CUT--- would be the simplest thing to do. Besides x + delta - x being strange-looking and running the risk of being manually (and incorrectly) changed to just delta the reference (not) cited above suggests to use a two- or three-steps procedure to ensure that some optimizing compiler will not do the same: ---CUT--- double sum = x + delta; dummy(sum); // function "dummy" does nothing. delta = sum - x; ---CUT--- Thus, I initially intended to add a utility method in "MathPrecision": ---CUT--- public static double representableDelta(double x, double originalDelta) { final long sum = Double.doubleToLongBits(x + originalDelta); final double delta = Double.longBitsToDouble(sum) - x; return delta; } ---CUT--- assuming that it is sufficiently "complicated" to evade the "smartest" JIT compiler. Then, I also implemented the simple thing: ---CUT--- public static double representableDelta2(double x, double originalDelta) { return x + originalDelta - x; } ---CUT--- Remarkably (or not), a trivial unit test (10^8 random delta values) did not find an occurrence where the returned values from one or the other method would differ. I think that the utility would be a useful addition to CM, if just to draw attention to the issue of accuracy in numerical derivatives[1], but I wonder whether the simple implementation is ensured to always work: I.e. does a rule exist that states that no optimization may ever be perfomed to simplify "x + delta - x" into "delta"? Any thoughts? (even if only for a better name...) Gilles [1] A better way would have been to have the numerical derivatives framework that someone had promised to contribute a few months ago... --------------------------------------------------------------------- To unsubscribe, e-mail: dev-unsubscr...@commons.apache.org For additional commands, e-mail: dev-h...@commons.apache.org