Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A good way to do a fast divide in C++?

Sometimes I see and have used the following variation for a fast divide in C++ with floating point numbers.

// orig loop
double y = 44100.0;
for(int i=0; i<10000; ++i) {
double z = x / y;
}

// alternative
double y = 44100;
double y_div = 1.0 / y;

for(int i=0; i<10000; ++i) {
double z = x * y_div;
}

But someone hinted recently that this might not be the most accurate way.

Any thoughts?

like image 902
Stephen Blinkhorn Avatar asked May 22 '09 20:05

Stephen Blinkhorn


People also ask

How do you divide in C?

printf("Enter dividend: "); scanf("%d", &dividend); printf("Enter divisor: "); scanf("%d", &divisor); Then the quotient is evaluated using / (the division operator), and stored in quotient . quotient = dividend / divisor; Similarly, the remainder is evaluated using % (the modulo operator) and stored in remainder .


2 Answers

On just about every CPU, a floating point divide is several times as expensive as a floating point multiply, so multiplying by the inverse of your divisor is a good optimization. The downside is that there is a possibility that you will lose a very small portion of accuracy on certain processors - eg, on modern x86 processors, 64-bit float operations are actually internally computed using 80 bits when using the default FPU mode, and storing it off in a variable will cause those extra precision bits to be truncated according to your FPU rounding mode (which defaults to nearest). This only really matters if you are concatenating many float operations and have to worry about the error accumulation.

like image 72
Not Sure Avatar answered Nov 15 '22 21:11

Not Sure


Wikipedia agrees that this can be faster. The linked article also contains several other fast division algorithms that might be of interest.

I would guess that any industrial-strength modern compiler will make that optimization for you if it is going to profit you at all.

like image 28
mwigdahl Avatar answered Nov 15 '22 21:11

mwigdahl