Loss of precision errors in FP conversions

bearophile bearophileHUGS at lycos.com
Tue Apr 19 17:37:47 PDT 2011


dsimcha:

> I know what you suggest could prevent bugs in a lot of 
> cases, but it also has the potential to get in the way in a lot of cases.

You are right, and I am ready to close that enhancement request at once if the consensus is against it.

double->float and real->float cases are not so common. How often do you use floats in your code? In my code it's uncommon to use floats, generally I use doubles.

A problem may be in real->double conversions, because I think D feels free to use intermediate real values in some FP computations.

Another possible problem: generic code like this is going to produce an error because 2.0 literal is double, so x*2.0 is a double even if x is float:

T foo(T)(T x) {
    return x * 2.0;
}

But when I use floats, I have found it good a C lint that spots double->float conversions, because it has actually allowed me to speed up some code that was doing float->double->float conversions without me being aware of it.


> A warning _may_ be appropriate, but definitely not an error.

Another option is a -warn_fp_precision_loss compiler switch, that produces warnings only when you use it. For my purposes this is is enough.


Regarding the actual amount of troubles this errors messages are going to cause, I have recently shown a link that argues for quantitative analysis of language changes:
http://www.digitalmars.com/webnews/newsgroups.php?art_group=digitalmars.D&article_id=135049
The idea here is to introduce those three FP conversions errors, compile Phobos and some other D2 code, and count how many problems it causes.

Bye,
bearophile


More information about the Digitalmars-d mailing list