Multiply floats and maintain / obtain precision with double precision

I have a function that accepts a float, I do some calculations with them, and I would like to keep as much accuracy as possible in the returned result. I read that when you multiply two floats, you double the number of significant digits.

So, when two floats get multiplication, for example, float e, f;and I do double g = e * fwhen the bits are truncated?

In my sample function below, I need casting, and if so, where? This is in a tight inner loop, if I put static_cast<double>(x)around every variable a b c dwhere it is used, I get 5-10% slowdown. But I suspect that I do not need to throw each variable separately, and only in some places, if at all? Or is the return of the double here not giving me any benefit in any way, and can I just return the float?

double func(float a, float b, float c, float d) {
    return (a - b) * c + (a - c) * b;
}
+4
source share
2 answers

When you multiply two floats without casting, the result is calculated with floating-point precision (i.e., truncated), and then converted to double.

double, . double ( float ). . , , , float double ( ).

, ( double , float vs double , ).

Btw. , / - . / 1e + 6 1e-3.

+5

5-10% . :

double func_impl(double a, double b, double c, double d) {
    return (a - b) * c + (a - c) * b;
}

double func(float a, float b, float c, float d) {
    return func_impl(a, b, c, d);
}

, , , ​​ ; ( ).

+4

Source: https://habr.com/ru/post/1654270/


All Articles