Should I use the decimal type as keys in a dictionary?

I am going to create a dictionary where each value has a numeric key obtained by experimental calculation.

I know that doubleany other type of floating point is not suitable for use as a key, since it is difficult to compare two floating point numbers with respect to uniqueness or equality.

Does anyone know if Decimalthis is a good candidate in this regard? An alternative would be to convert double to string with the given precision, but that sounds to me like an inelegant workaround.

+5
source share
3 answers

There is not much difference between using floator decimalas a dictionary. Both represent a number with an exponent - so both suffer from the same comparison problem only at different scales.

Either it would be good for the Dictionary, if you need bitwise equality, if you need keys for "about the same value", you need to make it a custom key that would round the values ​​in some known way, so that similar results the same bucket .. .

+6
source

If you use decimalor doublebecause it is intnot large enough, use instead long.

, , decimal double , / (-1,0,1,2,3 ..)

( decimal/double, , )

6 , int .

+2

, , , -.

.

, , , ( , , , 1.0 0.999998, ). (, , OP), , .

:

float Quantize(float x)
{
    const float relMaxQuantError = 0.001f;

    float ret = Mathf.Log10(Mathf.Abs(x));
    float quantum = Mathf.Log10(1+relMaxQuantError); 
    ret = Mathf.Floor(ret/quantum) * quantum;
    ret = Mathf.Sign(x) * (Mathf.Pow(10, ret));

    return ret;
}

float, , . ( 0,1%).

PS: Mathf - Unity. , Math.

+1

All Articles