llvm/llvm-project

Addressing `-Wimplicit-float-conversion` warning might lead to precision loss

Open

#93.288 aberto em 24 de mai. de 2024

Ver no GitHub
 (18 comments) (0 reactions) (0 assignees)C++ (10.782 forks)batch import
clang:diagnosticsenhancementgood first issue

Métricas do repositório

Stars
 (26.378 stars)
Métricas de merge de PR
 (Mesclagem média 1d 2h) (1.000 fundiu PRs em 30d)

Description

Disclaimer: My knowledge about floating-point precision is quite limited and I based most of my interpretations on the linked discussion. I came across this by accident and was wondering if there was something of the short-coming that could be detected by tooling. While looking into this I encountered this apparent issue.

This is based on the discussion in https://gitlab.freedesktop.org/mesa/mesa/-/merge_requests/28336.

According to that discussion the floating-point result of 48 * (1 / 255) should be 0.18823529779911041259765625. But if you simply write that it will lead to a compiler warning.

float f = 48 * (1.0 / 255.0);
warning: implicit conversion loses floating-point precision: 'double' to 'float' [-Wimplicit-float-conversion]
   12 |     float f = 48 * (1.0 / 255.0);
      |           ~   ~~~^~~~~~~~~~~~~~~

The obvious fix looks like adding the f suffix to the literals.

float f = 48 * (1.0f / 255.0f);

That fixes the warning but it changes the result to 0.1882353127002716064453125 which is supposedly less precise.

It took me quite a while until I finally came up with a solution which did not produce any warnings as well as the expected result.

float f = (float)(48 * (1.0 / 255.0));

As there are several ways to suppress (I do not consider it a fix when it changes the result/behavior) this warning seems likely to cause more harm than good so I thought it might be worth raising this issue.

See https://godbolt.org/z/crnKhzsec for all my attempts to mitigate this warning.

Guia do colaborador