为什么切换位后NaN是两倍?

时间:2019-06-16 18:06:54

标签: c# genetic-algorithm

我正在编写一种遗传算法,用于查找具有给定X,Y点的系数。此页面上描述了操作原理-https://towardsdatascience.com/introduction-to-genetic-algorithms-including-example-code-e396e98d8bf3

我有问题,因为有时在突变或交叉后,我的双精度值是NaN。

我尝试使用byte []和BitArray来执行此操作,但是在两种方法中我都得到相同的结果。

转换双精度<-> BitArray:

public void ConvertByteArrayToCoefficients(BitArray array)
{
    Coefficients.Clear(); //Coefficients are stored in List<double>

    for (int i = 0; i < _degree + 1; i++)
    {
        var arr = array.ToByteArray();
        double value = BitConverter.ToDouble(array.ToByteArray(), i * sizeof(double));

        Coefficients.Add(value);
    }
}

public BitArray GetAllCoefficientsInBytes()
{
    BitArray bytes = new BitArray(0);

    for (int i = 0; i < Coefficients.Count; i++) //append is extension method
        bytes = bytes.Append(new BitArray(BitConverter.GetBytes(Coefficients[i])));

    return bytes;
}

突变:

public void Mutate(int percentageChance)
{
    BitArray bytes = GetAllCoefficientsInBytes();

    for (int i = 0; i < bytes.Length; i++)
    {
        if (_randomProvider.Next(0, 100) < percentageChance)
        {
            if (bytes.Get(i))
                bytes[i] = false;
            else
                bytes[i] = true;
         }
    }

    ConvertByteArrayToCoefficients(bytes);
}

Crossover-每两个多项式调用一次的方法:

private void CrossoverSingle(Polynomial poly1, Polynomial poly2)
{
    int cutPosition = _randomProvider.Next(1, (_degreeOfPolynomial + 1) * sizeof(double) * 8);

    BitArray bytesOne = poly1.GetAllCoefficientsInBytes();
    BitArray bytesTwo = poly2.GetAllCoefficientsInBytes();

    for (int i = bytesOne.Length-1; i >= cutPosition; i--)
    {
        bool bitOne = bytesOne[i];
        bool bitTwo = bytesTwo[i];

        if (bitOne != bitTwo)
        {
            bytesOne[i] = bitTwo;
            bytesTwo[i] = bitOne;
        }
    }

    _crossoveredChildren.Add(new Polynomial(_randomProvider, _degreeOfPolynomial, bytesOne));
    _crossoveredChildren.Add(new Polynomial(_randomProvider, _degreeOfPolynomial, bytesTwo));
}

所有代码都在github上:https://github.com/Makulak/CoefficientsFinder 也许您知道为什么会这样吗?

1 个答案:

答案 0 :(得分:4)

这是因为您使用随机字节来生成IEEE-754数字。您不应该这样做,因为IEEE-754定义了这些数字的结构,并且使用随机字节输入不会为您提供随机数字,因为某些位表示诸如is Not-a-Number字段之类的内容,并且NaN值是“病毒”且无效其他计算。

要生成随机的Double数字,应使用System.Random.NextDouble()

相关问题