C & C++

C & C++

By DeepSource

Implicit type promotion of float to double in a math function CXX-P2001

Performance

Calling math functions that only accept double with float arguments causes an implicit type promotion of float argument. Type promoting float to double costs extra space in memory, it also costs extra instructions for the conversion from float and lastly vectorisation of float is a lot more efficient compared to double.

Consider using the math functions from standard that provide overloaded interfaces to accept float directly. In case you are using pure C, you should use the f suffixed math functions, to use the float accepting api. Eg, sinf, cosf, etc.

In case you still want to use doubles, you should consider making the cast to double explicit or ensure that passed argument is a double by default.

Bad practice

double acos(double);
double log(double);
double cosh(double);

void foo(float a) {
    acos(a);
    log(a);
    cosh(a);
}

Recommended

#include <cmath>
void foo(float a) {
    /// sample using explicit cast to `double`
    acos((double)a);
    log((double)a);
    cosh((double)a);
}

void bar(double a) {
    /// sample using variable of tyoe `double`
    acos(a);
    log(a);
    cosh(a);
}

void baz(float a) {
    /// sample using standard method with support for type `float`
    std::acos(a);
    std::log(a);
    std::cosh(a);
}

void car(float a) {
    /// sample using C function with support for type `float`
    acosf(a);
    logf(a);
    coshf(a);
}