在-1和1内生成随机浮点数会产生NaN

时间:2013-04-13 15:59:24

标签: java random floating-point

我需要生成-1和1范围内的浮点数。我正在使用这一行:

 weights[i] = random.nextFloat() * (weightMax - weightMin) + weightMin;

其中weightMax = 1weightMin = -1

但偶尔会产生NaNs。我该如何防止这种情况发生?

编辑: 是的,你是对的。我后来这样做了:

private void run_neural_network(double[] inputs, double[] outputs) {
    int i, j;
    int weight_counter = 0;

    for (i = 0; i < NB_OUTPUTS; i++) {
        double sum = 0.0;
        for (j = 0; j < NB_INPUTS; j++) {
            sum += inputs[j] * weights[weight_counter];
            weight_counter++;
        }
        outputs[i] = (Math.tanh(sum + weights[weight_counter]));
        weight_counter++;
    }
}

sum是NaN的来源:

[EpuckController] inputs0: 0.0, weight0 0.06174159,
[EpuckController] inputs1: 306.1555543759677, weight1 -7.409203E-23,
[EpuckController] inputs2: 0.0, weight2 1.2461361E-29,
[EpuckController] inputs3: 307.56460985278545, weight3 194105.33,
[EpuckController] inputs4: 0.0, weight4 0.41100776,
[EpuckController] inputs5: 0.0, weight5 0.0013858302,
[EpuckController] inputs6: 320.0046791338875, weight6 -1.49799987E14,
[EpuckController] inputs7: 0.0, weight7 195593.81,
[EpuckController] inputs8: 421.5353365457416, weight8 -0.8191289,
[EpuckController] Sum NaN

1 个答案:

答案 0 :(得分:3)

我强烈怀疑NaN来自其他地方 - 例如由于以后对重量进行分割操作。

虽然它肯定不是证据,但我已经创造了十亿个花车而没有看到你建议的行为:

import java.util.*;

public class Test {
    public static void main(String[] args) {
        Random random = new Random();
        for (int i = 0; i < 1000000000; i++) {
            float f = random.nextFloat() * 2 - 1;
            if (Float.isNaN(f)) {
                System.out.println("NaN!");
            }
        }
    }
}

(当然,它不会使有意义您提供的代码会产生NaN。)

我建议您在阵列分配后立即添加Float.isNaN测试。如果你然后看到它,但你稍后再看,那么问题显然是你正在用权重做的事情,而不是权重本身