Incompatible operand types String[] to int - incompatibletypeerror

Incompatible operand types String[] to int. I added divide and conquer algorithm to my project but I don't know is it good entegration? My project related about the finding the shortest way to x-y coordinate for cities and this project can be related about 3 algorithms for instance; divide and conquer strategy
greedy algorithm
nearest neighbor algorithm
package formalProject;
import java.io.*;
import java.io.FileNotFoundException;
import java.util.*;
public class Main {
public static void main (String[] args) throws FileNotFoundException{
String[][] cities = readArray("att48_xy.txt");
//printing cities 2d array
for(int i = 0; i < cities.length ; i++){
System.out.println(cities[i][0] + " " + cities[i][1]);
}
}
public static String[][] readArray(String file) throws FileNotFoundException{
//we'll count how many elements are there?
int counter = 0; //counter for calculating text's row length
Scanner sc1 = new Scanner(new File(file)); //scanner for calculating text's row length
while(sc1.hasNextLine()){ //checks for if there is any line
counter++;
sc1.nextLine();//jumps to next line
}
String[][] cities = new String[counter][2]; //creating our cities array with
//rows as "counter" and columns as 2(X, Y)
Scanner sc2 = new Scanner(new File(file)); //scanner for getting values from text
int i = 0;
while(sc2.hasNext()) {
String tempX = sc2.next();//first next will be X coordinate
String tempY = sc2.next();//second next will be Y coordinate
cities[i][0] = tempX;
cities[i][1] = tempY;
i++;
}
return cities; //returns our 2d array
}
public static int cities1 (String[][] cities){
if(cities.length==0 || cities.length==1){
return 0;
}
else{
return cities(cities,1,cities.length);
}
}
public static int cities(String[][] cities,int i,int f){
int m,result,sx,dx;
if(i>=f){
return 0;
}
else{
m=(i+f)/2;
sx=cities(cities,i,m);
dx=cities(cities,m+1,f);
result=sx+dx;
if((cities[m]==cities[m+1])&&(cities[m]==0)) //problem is here
result++;
return result;
}
}
}

cities[m] is an array. I think you possibly want cities[m].length here.

Related

How can I scale a unity sprite programmatically to a fractional number of units?

I've spawned a tile as follows:
private GameObject SpawnTile(int col, int row, Color color, GameObject parent, string label)
{
GameObject g = new GameObject("C: " + col + " R: " + row);
g.transform.position = world_grid.GetWorldPosition(col, row);
g.transform.localScale = new Vector3(world_grid.cell_size, world_grid.cell_size);
g.transform.parent = parent.transform;
return g;
}
I then add a spriterenderer, and display a sprite of a given color.
tile.game_object = SpawnTile(col, row, color, parent, label);
tile.sprite_renderer = tile.game_object.AddComponent<SpriteRenderer>();
tile.sprite_renderer.sprite = tile_sprite;
//Bounds bounds = tile.sprite_renderer.bounds;
tile.sprite_renderer.color = color;
I have the ability to display grids using this mechanism. I can scale the size of a tile up by an integer amount. However when I try to scale the object down, the sprite does not scale down with it.
In the following, I have 3 1x1 grids. The grid on the right has a cell_size of 2. The grid in the middle has a cell_size of 1. The grid on the left has a cell_size of 0.5.
The "tile" object is of an appropriate size. As we see this object is shown as half size in Unity's Scene View. However in the game view on the right, it shows as the same size as the pink grid in the middle.
Further details, I have spent quite a bit of time trying to figure this out, and though I see a variety of posts that seem to relate to sprite sizing, none of them are clear for a relative unity beginner.
Some of the posts I've found seem to suggest that I need to use the sprite renderer bounds to ensure that the sprite is proeprly sized. But its not clear to me how.
This is my grid class. Notice that it is constructed with a cell_size (in units). Notice that when I create the object of a given size, I size the object, but not the sprite.
public class WorldGrid<TGridObject> : Grid<TGridObject>
{
public float cell_size { get; private set; }
// Defines the center point in world coordinates
public Vector3 center_point { get; private set; }
public WorldGrid(Vector3 _center_point, int _columns, int _rows, float _cell_size) : base(_columns, _rows)
{
cell_size = _cell_size;
center_point = _center_point;
}
public Vector3 GetWorldPosition(int col, int row)
{
float x_pos = col * cell_size + cell_size / 2f;
float y_pos = row * cell_size + cell_size / 2f;
// wp = cp + gp
return center_point + new Vector3(x_pos, y_pos);
}
public void GetGridPosition(Vector3 world_position, out int col, out int row)
{
// gp = wp - cp
// position in grid-centered reference frame
Vector3 gp = world_position - center_point;
row = Mathf.FloorToInt(gp.y / cell_size);
col = Mathf.FloorToInt(gp.x / cell_size);
}
public void SetValue(Vector3 world_position, TGridObject value)
{
int row, col;
GetGridPosition(world_position, out row, out col);
SetValue(row, col, value);
}
}
This references a lower level grid class (that is not in world units):
public class Grid<TGridObject>
{
public int columns { get; private set; }
public int rows { get; private set; }
public TGridObject[,] grid { get; private set; }
private int cnt = 0;
public event EventHandler<OnGridCellValueChangedEventArgs> OnGridCellValueChanged;
public class OnGridCellValueChangedEventArgs : EventArgs
{
public int cnt;
public int row;
public int column;
}
public Grid(int _columns, int _rows)
{
columns = _columns;
rows = _rows;
grid = new TGridObject[columns, rows];
}
public void SetValue(int col, int row, TGridObject value)
{
if((row >= 0 && row < rows) &&
(col >= 0 && col < columns))
{
grid[col, row] = value;
if(OnGridCellValueChanged != null)
{
cnt += 1;
Debug.LogError("Triggering [" + col + "," + row + "] of [" + columns + "," + rows + "]");
OnGridCellValueChanged(this,
new OnGridCellValueChangedEventArgs { row = row, column = col, cnt = cnt }
);
}
}
}
public TGridObject GetValue(int col, int row)
{
if ((row >= 0 && row < rows) &&
(col >= 0 && col < columns))
{
return grid[col, row];
} else
{
return default(TGridObject);
}
}
}
I instantiate grids using a GridManager class:
public class GridManager : MonoBehaviour
{
[System.Serializable]
private struct WorldGridDescriptor
{
public int rows;
public int columns;
public float cell_size;
public Vector3 center_point;
public bool randomize_start;
}
public Sprite tile_sprite;
public int world_size_factor = 1;
private int columns, rows;
private float unit_step_size = 1.0f;
private List<WorldGrid<float>> world_grids = new List<WorldGrid<float>>();
private List<GridView> world_grid_views = new List<GridView>();
[SerializeField] private List<WorldGridDescriptor> world_grid_descriptors;
// Start is called before the first frame update
void Start()
{
// The orthographic size specifies the camera units from
// the horizontal centerline to the top of screen
// The vertical_units are then the number of tile rows
// from the centerline to the top of screen
rows = (int)Camera.main.orthographicSize * world_size_factor * 2;
float aspect_ratio = ((float)Screen.width / (float)Screen.height);
columns = (int)(rows * aspect_ratio);
// Will parent the tiles in the empty Grid.
// Perhaps this container should be public.
// For now it is a hard-coded assumption, that it exists.
GameObject grid_container = this.gameObject.transform.Find("Grid").gameObject;
if (world_grid_descriptors != null)
{
foreach (WorldGridDescriptor wgd in world_grid_descriptors)
{
WorldGrid<float> wg = new WorldGrid<float>(wgd.center_point, wgd.columns, wgd.rows, wgd.cell_size);
if(wgd.randomize_start)
{
RandomizeState(wg);
}
GridView grid_view = new GridView(wg, tile_sprite, grid_container);
world_grids.Add(wg);
world_grid_views.Add(grid_view);
}
}
}
private void RandomizeState(WorldGrid<float> g)
{
for (int col = 0; col < g.columns; col++)
{
for (int row = 0; row < g.rows; row++)
{
g.SetValue(col, row, Random.Range(0.0f, 1.0f));
}
}
}
private void Update()
{
if (Input.GetMouseButtonDown(0)) {
Vector3 worldPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
foreach (WorldGrid<float> wg in world_grids)
{
int c, r;
wg.GetGridPosition(worldPosition, out c, out r);
wg.SetValue(c, r, Random.Range(0.0f, 1.0f));
}
}
}
}
Lastly, the view into the grids are created as follows (this shows you exactly how I create the grid representation that uses a sprite renderer component to render sprites for each cell in the grid):
public class GridView
{
public struct Tile
{
public GameObject game_object;
public SpriteRenderer sprite_renderer;
public TextMesh text_mesh;
}
private Tile[,] tiles;
private WorldGrid<float> world_grid;
protected Sprite tile_sprite { get; private set; }
public GridView(WorldGrid<float> wg, Sprite ts, GameObject parent)
{
world_grid = wg;
tile_sprite = ts;
tiles = new Tile[wg.columns, wg.rows];
wg.OnGridCellValueChanged += OnGridCellValueChanged;
Create(parent);
}
private void Create(GameObject parent)
{
for (int col = 0; col < world_grid.columns; col++)
{
for (int row = 0; row < world_grid.rows; row++)
{
Tile tile = new Tile();
float r, g, b;
r = g = b = world_grid.grid[col, row];
float a = 1f;
Color color = new Color(r, g, b, a);
string label = (string)((int)(255 * world_grid.grid[col, row])).ToString("x");
tile.game_object = SpawnTile(col, row, color, parent, label);
tile.sprite_renderer = tile.game_object.AddComponent<SpriteRenderer>();
tile.sprite_renderer.sprite = tile_sprite;
//Bounds bounds = tile.sprite_renderer.bounds;
tile.sprite_renderer.color = color;
tile.text_mesh = UtilsClass.CreateWorldText(label, parent.transform,
tile.game_object.transform.position, 7, Color.red, TextAnchor.MiddleCenter);
tiles[col, row] = tile;
}
}
}
// Update is called once per frame
private GameObject SpawnTile(int col, int row, Color color, GameObject parent, string label)
{
GameObject g = new GameObject("C: " + col + " R: " + row);
g.transform.position = world_grid.GetWorldPosition(col, row);
g.transform.localScale = new Vector3(world_grid.cell_size, world_grid.cell_size);
g.transform.parent = parent.transform;
return g;
}
private void OnGridCellValueChanged(object sender, Grid<float>.OnGridCellValueChangedEventArgs e)
{
Debug.LogError(e.cnt + " - Updating [" + e.column + "," + e.row + "]");
Update(e.row, e.column);
}
private void Update(int row, int col)
{
if (row >= 0 && row < world_grid.rows && col >= 0 && col < world_grid.columns)
{
Tile tile = tiles[col, row];
float r, g, b;
r = g = b = world_grid.grid[col, row];
float a = 1f;
Color color = new Color(r, g, b, a);
string label = (string)((int)(255 * world_grid.grid[col, row])).ToString("x");
tile.text_mesh.text = label;
tile.sprite_renderer.color = color;
}
}
}
My sprites are a simple blank image that is 256 x 256 pixels in size. I then set the pixels per unit (in the unity editor) to 256.
How can I scale the sprite so that it aligns properly with the spawned tile?
Looks like my only issue was in the Display setting.
I had been using a 10x10 display.
When I changed it to something more reasonable, I realized that my gameobjects were being displayed and selected as expected.

How to use selection sort in objects and classes

I'm creating two classes called stop watch and random numbers, which I have already done, but I needed to create a test program that would measure the execution time of sorting 100,000 numbers using selection sort. I know how to create a selection sort, I just don't know how to take the random numbers class and put it together with the selection sort, I get the error message "incompatible types random numbers cannot be converted to int" I hope someone can help me.
My random numbers class
import java.util.Random;
public class randomnumbers {
Random ran1 = new Random();
private int size;
public randomnumbers(){
size = 100000;
}
public int getSize(){
return size;
}
public void setSize(int newSize){
size = newSize;
}
public int [] createArray(int [] size){
for (int i = 0; i < size.length; i++){
size[i] = ran1.nextInt();
}
return size;
}
public static void printArray (int [] array){
for (int i = 0; i < array.length; i++){
if (i < 0){
System.out.println(array[i] + " ");
}
}
}
}
My test Program
public static void main (String [] args){
// Create a StopWatch object
StopWatch timer = new StopWatch();
//create random numbers
randomnumbers numbers = new randomnumbers();
//Create the size of the array
numbers.getSize();
// Invoke the start method in StopWatch class
timer.start();
//sort random numbers
selectionSort();
// Invoke the stop method in StopWatch class
timer.stop();
// Display the execution time
System.out.println("The execution time for sorting 100,000 " +
"numbers using selection sort: " + timer.getElapsedTime() +
" milliseconds");
}
// selectionSort performs a selection sort on an array
public static void selectionSort(int[] array) {
for (int i = 0; i < array.length - 1; i++) {
int min = array[i];
int minIndex = i;
for (int j = i + 1; j < array.length; j++) {
if (array[j] < min) {
min = array[j];
minIndex = j;
}
}
if (i != minIndex) {
array[minIndex] = array[i];
array[i] = min;
}
}
}
}
Where exactly are you getting "incompatible types random numbers cannot be converted to int" error?
There are multiple issues with the code:
Unconventional naming
size field is in randomnumbers class is used as actual array size in constructor but in createArray it's overshadowed with a parameter of the same name but different type and meaning.
You are not passing any array to selectionSort in Main. This is where I get compile error on your code.
printArray has if (i < 0) condition that is false for all ran1.nextInt() numbers so it will not print anything.
Feeding selectionSort with numbers.createArray(new int[numbers.getSize()]) compiles and ends up sorting the array.

mergsort printing a strange result

I am having an issue with my merge sort, when I print out my sortedArray it only returns [ 0.0, 0.0.....] Im not sure if there is an error in my sort code or in my print line or if it has to do with doubles. The code I am us posted below.
By calling System.out.println(toString(sortedArray) I get an even more obscure answer.
Thanks for any help.
package mergesort;
import java.util.Arrays;
import java.util.Random;
public class mergesort {
public static void main(String[] args) {
double[] array = getIntArray();
long before = System.nanoTime();
double[] sortedArray= mergeSort(array);
System.out.println("Sorting took "+ (System.nanoTime() - before) +" nanoseconds ");
System.out.println(toString(array) + "\n\n" + toString(sortedArray) + "\n main method completed in: " + (System.nanoTime() - before) + " nanoseconds.");
}
private static String toString(double[] array) {
StringBuilder sb = new StringBuilder("[ ");
double len = array.length;
for(int i = 0; i < len - 1; i++) {
sb.append(array[i] + ", ");
}
sb.append(array[(int) (len - 1)] + " ]");
return sb.toString();
}
public static double[] mergeSort(double[] array) {
if (array.length <= 1) {
return array;
}
int half = array.length / 2;
return merge(mergeSort(Arrays.copyOfRange(array, 0, half)),
mergeSort(Arrays.copyOfRange(array, half, array.length)));
}
private static double[] merge(double[] ds, double[] ds2) {
int len1 = ds.length, len2 = ds2.length;
int totalLength = len1 + len2;
double[] result = new double[totalLength];
int counterForLeft =0,counterForRight=0,resultIndex=0;
while(counterForLeft<len1 || counterForRight < len2){
if(counterForLeft<len1 && counterForRight < len2){
if(ds[counterForLeft]<= ds2[counterForRight]){
result[resultIndex++] =(int) ds[counterForLeft++];
} else {
result[resultIndex++] =(int) ds2[counterForRight++];
}
}else if(counterForLeft<len1){
result[resultIndex++] = (int) ds[counterForLeft++];
}else if (counterForRight <len2){
result[resultIndex++] =(int) ds2[counterForRight++];
}
}
return result;
}
private static double[] getIntArray() {
double[] array = new double[10000];
Random random = new Random();
for(int i = 0; i < 10000; i++) {
array[i] = (random.nextDouble() * .99999);
}
return array;
}
}
In the merge method, when copying from one of the input arrays to the results, you cast to int. For example:
result[resultIndex++] =(int) ds[counterForLeft++];
All your doubles are in the range [0...1), so the result of casting any of them to int is zero. Just get rid of those casts, and you will keep your numbers in the merge result.
As an additional tip, it is much easier to debug small problems than large ones. It failed for any size greater than 2, so you should have been debugging with size 2, not 10000.

Attempts to call a method in the same class not working (java)

I'm creating a random number generator which then sorts the digits from largest to smallest. Initially it worked but then I changed a few things. As far as I'm aware I undid all the changes (ctrl + z) but now I have errors at the points where i try to call the methods. This is probably a very amateur problem but I haven't found an answer. The error i'm met with is "method in class cannot be applied to given types"
Here's my code:
public class RandomMath {
public static void main(String[] args) {
String bigger = bigger(); /*ERROR HERE*/
System.out.println(bigger);
}
//create method for generating random numbers
public static int generator(int n){
Random randomGen = new Random();
//set max int to 10000 as generator works between 0 and n-1
for(int i=0; i<1; i++){
n = randomGen.nextInt(10000);
// exclude 1111, 2222, 3333, 4444, 5555, 6666, 7777, 8888, 9999, 0000
if((n==1111 || n==2222 || n==3333 || n ==4444 || n==5555)
||(n==6666 || n==7777 || n==8888 || n==9999 || n==0000)){
i--;
}
}
return n;
}
//create method for denoting the bigger number
public static String bigger(int generated){
generated = generator(); /*ERROR HERE*/
System.out.println(generated);
int[] times = new int[10];
while (generated != 0) {
int val = generated % 10;
times[val]++;
generated /= 10;
}
String bigger = "";
for (int i = 9; i >= 0; i--) {
for (int j = 0; j < times[i]; j++) {
bigger += i;
}
}
return bigger;
}
}
You have not defined a method bigger(), only bigger(int generated). Therefore, you must call your bigger method with an integer parameter.

Java based Neural Network --- how to implement backpropagation

I am building a test neural network and it is definitely not working. My main problem is backpropagation. From my research, I know that it is easy to use the sigmoid function. Therefore, I update each weight by (1-Output)(Output)(target-Output) but the problem with this is what if my Output is 1 but my target is not? If it is one at some point then the weight update will always be 0...For now I am just trying to get the darn thing to add the inputs from 2 input neurons, so the optimal weights should just be 1 as the output neuron simply adds its inputs. I'm sure I have messed this up in lots of places but here is my code:
public class Main {
public static void main(String[] args) {
Double[] inputs = {1.0, 2.0};
ArrayList<Double> answers = new ArrayList<Double>();
answers.add(3.0);
net myNeuralNet = new net(2, 1, answers);
for(int i=0; i<200; i++){
myNeuralNet.setInputs(inputs);
myNeuralNet.start();
myNeuralNet.backpropagation();
myNeuralNet.printOutput();
System.out.println("*****");
for(int j=0; j<myNeuralNet.getOutputs().size(); j++){
myNeuralNet.getOutputs().get(j).resetInput();
myNeuralNet.getOutputs().get(j).resetOutput();
myNeuralNet.getOutputs().get(j).resetNumCalled();
}
}
}
}
package myneuralnet;
import java.util.ArrayList;
public class net {
private ArrayList<neuron> inputLayer;
private ArrayList<neuron> outputLayer;
private ArrayList<Double> answers;
public net(Integer numInput, Integer numOut, ArrayList<Double> answers){
inputLayer = new ArrayList<neuron>();
outputLayer = new ArrayList<neuron>();
this.answers = answers;
for(int i=0; i<numOut; i++){
outputLayer.add(new neuron(true));
}
for(int i=0; i<numInput; i++){
ArrayList<Double> randomWeights = createRandomWeights(numInput);
inputLayer.add(new neuron(outputLayer, randomWeights, -100.00, true));
}
for(int i=0; i<numOut; i++){
outputLayer.get(i).setBackConn(inputLayer);
}
}
public ArrayList<neuron> getOutputs(){
return outputLayer;
}
public void backpropagation(){
for(int i=0; i<answers.size(); i++){
neuron iOut = outputLayer.get(i);
ArrayList<neuron> iOutBack = iOut.getBackConn();
Double iSigDeriv = (1-iOut.getOutput())*iOut.getOutput();
Double iError = (answers.get(i) - iOut.getOutput());
System.out.println("Answer: "+answers.get(i) + " iOut: "+iOut.getOutput()+" Error: "+iError+" Sigmoid: "+iSigDeriv);
for(int j=0; j<iOutBack.size(); j++){
neuron jNeuron = iOutBack.get(j);
Double ijWeight = jNeuron.getWeight(i);
System.out.println("ijWeight: "+ijWeight);
System.out.println("jNeuronOut: "+jNeuron.getOutput());
jNeuron.setWeight(i, ijWeight+(iSigDeriv*iError*jNeuron.getOutput()));
}
}
for(int i=0; i<inputLayer.size(); i++){
inputLayer.get(i).resetInput();
inputLayer.get(i).resetOutput();
}
}
public ArrayList<Double> createRandomWeights(Integer size){
ArrayList<Double> iWeight = new ArrayList<Double>();
for(int i=0; i<size; i++){
Double randNum = (2*Math.random())-1;
iWeight.add(randNum);
}
return iWeight;
}
public void setInputs(Double[] is){
for(int i=0; i<is.length; i++){
inputLayer.get(i).setInput(is[i]);
}
for(int i=0; i<outputLayer.size(); i++){
outputLayer.get(i).resetInput();
}
}
public void start(){
for(int i=0; i<inputLayer.size(); i++){
inputLayer.get(i).fire();
}
}
public void printOutput(){
for(int i=0; i<outputLayer.size(); i++){
System.out.println(outputLayer.get(i).getOutput().toString());
}
}
}
package myneuralnet;
import java.util.ArrayList;
public class neuron {
private ArrayList<neuron> connections;
private ArrayList<neuron> backconns;
private ArrayList<Double> weights;
private Double threshold;
private Double input;
private Boolean isOutput = false;
private Boolean isInput = false;
private Double totalSignal;
private Integer numCalled;
private Double myOutput;
public neuron(ArrayList<neuron> conns, ArrayList<Double> weights, Double threshold){
this.connections = conns;
this.weights = weights;
this.threshold = threshold;
this.totalSignal = 0.00;
this.numCalled = 0;
this.backconns = new ArrayList<neuron>();
this.input = 0.00;
}
public neuron(ArrayList<neuron> conns, ArrayList<Double> weights, Double threshold, Boolean isin){
this.connections = conns;
this.weights = weights;
this.threshold = threshold;
this.totalSignal = 0.00;
this.numCalled = 0;
this.backconns = new ArrayList<neuron>();
this.input = 0.00;
this.isInput = isin;
}
public neuron(Boolean tf){
this.connections = new ArrayList<neuron>();
this.weights = new ArrayList<Double>();
this.threshold = 0.00;
this.totalSignal = 0.00;
this.numCalled = 0;
this.isOutput = tf;
this.backconns = new ArrayList<neuron>();
this.input = 0.00;
}
public void setInput(Double input){
this.input = input;
}
public void setOut(Boolean tf){
this.isOutput = tf;
}
public void resetNumCalled(){
numCalled = 0;
}
public void setBackConn(ArrayList<neuron> backs){
this.backconns = backs;
}
public Double getOutput(){
return myOutput;
}
public Double getInput(){
return totalSignal;
}
public Double getRealInput(){
return input;
}
public ArrayList<Double> getWeights(){
return weights;
}
public ArrayList<neuron> getBackConn(){
return backconns;
}
public Double getWeight(Integer i){
return weights.get(i);
}
public void setWeight(Integer i, Double d){
weights.set(i, d);
}
public void setOutput(Double d){
myOutput = d;
}
public void activation(Double myInput){
numCalled++;
totalSignal += myInput;
if(numCalled==backconns.size() && isOutput){
System.out.println("Total Sig: "+totalSignal);
setInput(totalSignal);
setOutput(totalSignal);
}
}
public void activation(){
Double activationValue = 1 / (1 + Math.exp(input));
setInput(activationValue);
fire();
}
public void fire(){
for(int i=0; i<connections.size(); i++){
Double iWeight = weights.get(i);
neuron iConn = connections.get(i);
myOutput = (1/(1+(Math.exp(-input))))*iWeight;
iConn.activation(myOutput);
}
}
public void resetInput(){
input = 0.00;
totalSignal = 0.00;
}
public void resetOutput(){
myOutput = 0.00;
}
}
OK so that is a lot of code so allow me to explain. The net is simple for now, just an input layer and an output layer --- I want to add a hidden layer later but I'm taking baby steps for now. Each layer is an arraylist of neurons. Input neurons are loaded with inputs, a 1 and a 2 in this example. These neurons fire, which calculates the sigmoid of the inputs and outputs that to the output neurons, which adds them and stores the value. Then the net backpropagates by taking the (answer-output)(output)(1-output)(output of the specific input neuron) and updates the weights accordingly. A lot of times, it cycles through and I get infinity, which seems to correlate with negative weights or sigmoid. When that doesn't happen it converges to 1 and since (1-output of 1) is 0, my weights stop updating.
The numCalled and totalSignal values are just so the algorithm waits for all neuron inputs before continuing. I know I'm doing this an odd way, but the neuron class has an arraylist of neurons called connections to hold the neurons that it is forward connected to. Another arraylist called backconns holds the backward connections. I should be updating the correct weights as well since I am getting all back connections between neurons i and j but of all neurons j (the layer above i) I am only pulling weight i. I apologize for the messiness --- I've been trying lots of things for hours upon hours now and still cannot figure it out. Any help is greatly appreciated!
Some of the best textbooks on neural networks in general are Chris Bishop's and Simon Haykin's. Try reading through the chapter on backprop and understand why the terms in the weight update rule are the way they are.The reason why I am asking you to do that is that backprop is more subtle than it seems at first. Things change a bit if you use a linear activation function for the output layer (think about why you might want to do that. Hint: post-processing), or if you add a hidden layer. It got clearer for me when I actually read the book.
You might want to compare your code to this single layer perceptron.
I think you have a bug in your backprop algo. Also, try replacing the sigmoid with a squarewave.
http://web.archive.org/web/20101228185321/http://en.literateprograms.org/Perceptron_%28Java%29
what if my Output is 1 but my target is not?
The sigmoid function 1/(1 + Math.exp(-x)) never equates to 1. The lim as x approaches infinity is equal to 0, but this is a horizontal asymptote, so the function never actually touches 1. Therefore, if this expression is used to compute all of your output values, then your output will never be 1. So (1 - output) shouldn't ever equal 0.
I think your issue is during the calculation of the output. For a neural network, the output for each neuron is typically sigmoid(dot product of inputs and weights). In other words, value = input1 * weight1 + input2 * weight2 + ... (for each weight of neuron) + biasWeight. Then that neuron's output = 1 / (1 + Math.exp(-value). If it's calculated in this way, the output won't ever be equal to 1.