简体   繁体   English

从java循环总结产品

[英]Summing up products from java loop

I am having problems with summing up the products produced from my java loop.我在总结从我的 java 循环产生的产品时遇到问题。

public class ArtificialNeuron {

    public ArtificialNeuron(double[] weightings) {
        weights = weightings;
        inputs = new double[6];
        inputs[0] = 1;
    }

    public void setInput(int index, double newValue) {
        inputs[index] =  newValue;
    }

    public int activate(double threshold) {
        double x = 0;
        for(int i=0; i<inputs.length;i++)
            x = inputs[i]*weights[i];
        double sum = x+x+x+x+x+x;
        if(sum >= threshold) {
            return 1;
        } else {
            return -1;
        }
    }
}

I ran several Junit test and it always seem to fail on the if else statement.我运行了几个 Junit 测试,它似乎总是在 if else 语句上失败。 I believe it probably my summation method, but I don't know how I would sum up the products.我相信这可能是我的求和方法,但我不知道如何总结产品。

Based on your code, I think you wanted to add all of the products together.根据您的代码,我认为您想所有产品添加在一起。 Instead, you are multiplying the last product by 6 (effectively).相反,您将最后一个乘积乘以 6(有效)。 It's unclear why you have the temporary x , you can add each product to a default sum of 0 .不清楚为什么您有临时x ,您可以将每个产品添加到默认sum 0 Also, I think a test for sum < threshold is a little easier to read (likewise, always use braces with your loops - it's easier to read and reason about).另外,我认为sum < threshold的测试更容易阅读(同样,始终在循环中使用大括号 - 更容易阅读和推理)。 Like,喜欢,

public int activate(double threshold) {
    double sum = 0;
    for (int i = 0; i < inputs.length; i++) {
        sum += inputs[i] * weights[i]; // sum = sum + (inputs[i] * weights[i])
    }
    if (sum < threshold) {
        return -1;
    }
    return 1;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM