Fraser - 2 months ago 30

Java Question

I wrote out a sigmoid function in java that works fine when dealing with single numbers but when given an array fails after the first data entry.

Here's some data to Illustrate my problem (with output rounded to 3 digits).

`Input | Correct Output | Output`

0 | 0.5 | 0.5

-1,0 | 0.27,0.5 | 0.27,0.62

1,0,-1 | 0.73,0.5,0.27 | 0.73,0.62,0.64

My code is as follows.

`double[] data = { 1, 0, -1 };`

System.out.println(sigmoid(data)[0] + "," + sigmoid(data)[1] + "," + sigmoid(data)[2]);

and

`double[] sigmoid(double[] data) {`

for (int i = 0; i < data.length; i++)

data[i] = 1 / (1 + Math.exp(-data[i]));

return data;

}

If this is just a stupidly obvious oversight on my part please tell me as I have been trying for hours to no avail, and thanks for any responses at all.

Answer

While Java is pass by value, the value being passed to your function is a reference to the input array, not a copy of the array, so your function modifies the array in place - each call in your `println`

is updating the results from the previous call.

Make a copy of the array to return your results in:

```
static double[] sigmoid(double[] data) {
double[] z = Arrays.copyOf(data, data.length);
for (int i = 0; i < z.length; i++)
z[i] = 1 / (1 + Math.exp(-z[i]));
return z;
}
```