Question

I'm in the middle of porting some c++ code to java, and I keep running across instances where whoever wrote it kept doing the following:

double c = (1.0/(a+1.0)*pow(b, a+1.0));
double d = (1./(integral(gamma, dmax)-integral(gamma, dmin)))*(integral(gamma+1, dmax)-integral(gamma+1, dmin));

Instead of:

double c = pow(b, a+1.0)/(a+1.0);
double d = (integral(gamma+1, dmax)-integral(gamma+1, dmin))/(integral(gamma, dmax)-integral(gamma, dmin));

The second seems much clearer, and unless I'm wrong about the order of operations in C++ they should do the same thing. Is there some reason to do the first and not the second? The only thing I could think of would be some weird case with precision.

Was it helpful?

Solution

Yes, they're the same. The only reason I can think of is mathematical clarity: sometimes when you're normalizing a quantity, you often write:

answer = (1/total) * (some of it)

For example, Cauchy's integral theorem is often written

f(a) = (1/(2*pi*i)) * integral(f(z)/(z-a), dz)

OTHER TIPS

If a remains the same and b is changing (say, if your code is in a loop and it's clear that a does not change between two iterations, for instance because it's a const variable), then the original version can execute faster, because multiplication is cheaper than division (assuming the compiler moves the computation of 1/... out of the loop).

It seems like a misguided attempt at optimization if that's the reason, but it doesn't mean it is not it.

Oh, and regarding precision, the original version is in fact slightly less precise than yours, if anything, because there is an additional rounding error for the 1/.... It is this rounding error that prevents the compiler from transforming your version into the original version of its own volition: they do not compute exactly the same thing (but very close things).

Yes they should do the same thing. The original author may have been replicating equations found else where

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top