microsoft / qsharp-language

Official repository for design of the quantum programming language Q# and its core libraries
MIT License
233 stars 54 forks source link

Floating-point numbers with too long decimal places will lose precision #142

Open weucode opened 2 years ago

weucode commented 2 years ago

Description

When set a floating-point value with long demical places,it will move the decimal part forward by about one or more places,sometimes this will lead to some misunderstandings.

For example,if I use two different values to check whether they are equal to a same floating-point,the result values are all true,I'm not sure such behavior should be allowed.

Testcase

namespace NISLNameSpace {
    open Microsoft.Quantum.Intrinsic;

    @EntryPoint()
    operation main() : Unit {
        mutable num = 4.5423904623895424;
        Message($"check {num}" );
        if(num == 4.5423904623895424){
            Message("this is true");
        }
        if (num == 4.542390462389543) {
            Message("this is true too");
        }
    }
}

The output message is shown below.

check 4.542390462389543 this is true this is true too

bettinaheim commented 1 year ago

I am not sure I follow what concretely the question is? The behavior of doubles in Q# should match the behavior in other languages as well, including the standard limitations on precision. While hence generally the recommendation is to not compare floating point values for equality, usually languages allow to do so since for certain value this is perfectly safe and sometimes even necessary. I believe Q# follows standard practice in that regard.