llvm/llvm-project

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

Open

#93,288 opened on 2024年5月24日

GitHub で見る
 (18 comments) (0 reactions) (0 assignees)C++ (10,782 forks)batch import
clang:diagnosticsenhancementgood first issue

Repository metrics

Stars
 (26,378 stars)
PR merge metrics
 (平均マージ 1d 2h) (30d で 1,000 merged PRs)

説明

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.

コントリビューターガイド