So I have this piece of code:
private ArrayList<Triangle3D> combine(ArrayList<Triangle2D> leftTriangles, ArrayList<Triangle2D> rightTriangles) {
ArrayList<Triangle3D> returnTriangles = new ArrayList<Triangle3D>();
for (Triangle2D eL : leftTriangles){
Triangle2D eR = eL.getOtherTriangle(rightTriangles);
if(eR != null){
ArrayList<Point3d> corners = new ArrayList<Point3d>(3);
for(Tuple<Integer, Integer> cornerL : eL.getCorners()){
Tuple<Integer, Integer> cornerR = eR.getCorrespondingCorner(cornerL);
if(cornerL != cornerR){
corners.add(addDistances(cornerL, cornerR));
}
}
returnTriangles.add(new Triangle3D(corners, eL.getColor()));
}
}
return returnTriangles;
}
But for some reason whenever i excecute the line:
returnTriangles.add(new Triangle3D(corners, eL.getColor()));
The previous "corners" values of the Triangle3D elements that are already in the list get overriden by the newle added ones. Which I think is weird because I clearly make a new Arraylist on this line:
ArrayList<Point3d> corners = new ArrayList<Point3d>(3);
I defined the Tuple class myself as following:
package vision.polyhedradetection;
public class Tuple<X, Y> {
private final X x;
private final Y y;
public Tuple(X x, Y y) {
this.x = x;
this.y = y;
}
public X getX() { return x; }
public Y getY() { return y; }
public Tuple<X, Y> copy(){
return new Tuple<X,Y>(this.x, this.y);
}
#Override
public String toString() {
return "(" + x + "," + y + ")";
}
#Override
public boolean equals(Object other) {
if (other == this) {
return true;
}
if (!(other instanceof Tuple)){
return false;
}
Tuple<Integer, Integer> other_ = (Tuple<Integer, Integer>) other;
return other_.x == (this.x) && other_.y == (this.y);
}
}
EDIT:
I found the root of the problem. But still don't know how to fix it. It's in my Triangle3D class. This is my class:
package vision.polyhedradetection;
import javax.vecmath.Point3d;
import java.util.List;
public class Triangle3D {
private static Point3d corner1 = new Point3d();
private static Point3d corner2 = new Point3d();
private static Point3d corner3 = new Point3d();
private int color;
public Triangle3D(Point3d corner1, Point3d corner2, Point3d corner3, int color) {
this.corner1 = corner1;
this.corner2 = corner2;
this.corner3 = corner3;
this.color = color;
}
public Triangle3D(List<Point3d> corners, int color) {
this.corner1 = corners.get(0);
this.corner2 = corners.get(1);
this.corner3 = corners.get(2);
this.color = color;
}
private static Point3d centroid;
public Triangle3D(Point3d centroid, int color) {
this.centroid = centroid;
this.color = color;
}
public Point3d[] getCorners() {
Point3d[] Corners = {corner1, corner2, corner3};
return Corners;
}
public int getColor() {
return this.color;
}
public Point3d getCentroid() {
if (this.centroid != null) return this.centroid;
else {
Double x = (double) Math.round((corner1.x + corner2.x + corner3.x) / 3);
Double y = (double) Math.round((corner1.y + corner2.y + corner3.y) / 3);
Double z = (double) Math.round((corner1.z + corner2.z + corner3.z) / 3);
this.centroid = new Point3d(x, y, z);
return this.centroid;
}
}
}
The problem lies in this code in my combine function:
returnTriangles.add(new Triangle3D(corners, eL.getColor()));
For some reason when I create this new Triangle3D my corner1, corner2, corner3 in the "new" creating triangle are already set (thus they are pointing to my already existing corners). How do I get rid of this dependency? I don't get it since i make new corners when I create that class.
Can you provide me with example data where I can see the value being overridden?
ArrayList.add add an element, it does not replace an element.
Your corners is within the for loop scope, so it shouldn't save any previous data.
I do not think you have debugged it properly and mistakenly think that it replaces the previous value. I would gladly help you, but I need the same data as the data that you have used.
Related
I have created the class angle as shown in the codebox below, I want to calculate the difference( called "minus" in the code) of two angles with the following command.
Angle.degrees(135).minus(Angle.degrees(90)).getDegrees()
Unfortunately, I always get zero as result, because the intern values are always overwritten.
import java.lang.Math;
public class Angle {
private static double gradmass = 0;
private static double bogenmass = 0;
public static Angle degrees(double angle) {
Angle angleD = new Angle();
// gradmass = angle;
// bogenmass = Math.toRadians(angle);
angleD.setDegrees(angle);
angleD.setRadians(Math.toRadians(angle));
return angleD;
}
public static Angle radians(double angle) {
Angle angleR = new Angle();
// gradmass = Math.toDegrees(angle);
// bogenmass = angle;
angleR.setDegrees(Math.toDegrees(angle));
angleR.setRadians(angle);
return angleR;
}
public double getDegrees() {
return gradmass;
}
public void setDegrees(double gradM) {
gradmass = gradM;
}
public double getRadians() {
return bogenmass;
}
public void setRadians(double bogenM) {
bogenmass = bogenM;
}
public Angle plus(Angle other) {
Angle temp = new Angle();
temp.setDegrees(this.getDegrees() + other.getDegrees());
temp.setRadians(other.getRadians() + other.getRadians());
return temp;
}
public Angle minus(Angle other) {
Angle temp = new Angle();;
temp.setDegrees(this.getDegrees() - other.getDegrees());
temp.setRadians(this.getRadians() - other.getRadians());
return temp;
}
public Angle neg() {
Angle temp = new Angle();
temp.setDegrees(-this.getDegrees());
temp.setRadians(-this.getRadians());
return temp;
}
public double sin() {
double temp;
temp = Math.sin(this.getDegrees());
return temp;
}
public double cos() {
double temp;
temp = Math.cos(this.getDegrees());
return temp;
}
public boolean similarTo(Angle other){
boolean gleich = false;
if( 0 == (this.getDegrees() - other.getDegrees()) || this.neg().getDegrees() == other.getDegrees()){
gleich = true;
}
return gleich;
}
public String toString(){
return
"GradM " + this.getDegrees() + " BogenM " + this.getRadians();
}
}
I did not make a constructor on purpose! I'm looking for a solution without a constructor or nonstatic methods.
Both your data members are static, meaning there's a single instance of them for the entire class. You should declare them as instance members so that each instance of Angle can have its own values:
public class Angle {
private double gradmass = 0;
private double bogenmass = 0;
// rest of the code...
Don't do this. Your class won't be thread-safe this way. What you want is kind of something like BigDecimal class in java, I guess. You can check the documentation of BigDecimal class of java if you want something like this.
https://docs.oracle.com/javase/8/docs/api/java/math/BigDecimal.html
But if you want the exact same thing you asked, you can see this (not thread safe and not recommended as well).
class Angle {
static Double angle1 = null;
static Double angle2 = null;
private static void setAngle(double angle) {
if (angle1 == null) angle1 = angle;
else angle2 = angle;
}
static Angle degrees(Double angle) {
setAngle(angle);
return new Angle();
}
static Double getDegrees() {
return angle1;
}
static Angle minus(Angle angle) {
angle1 -= angle2;
return new Angle();
}
}
public class SolutionAngle {
public static void main(String... args) {
System.out.println(Angle.degrees(135).minus(Angle.degrees(90)).getDegrees());
}
}
I'm learning the concept of neural networks. I decided to try making the neuron class by myself. What is the best way to implement different activation functions in my code? Now it uses only the binary step function.
It's my first try in coding neural networks so if you have any suggestions about my code, or it is completely dumb, please let me know.
Here is my code:
public class Neuron {
// properties
private ArrayList<Neuron> input;
private ArrayList<Float> weight;
private float pot, bias, sense, out;
private boolean checked;
// methods
public float fire(){
pot = 0f;
if (input != null) {
for (Neuron n : input){
if (!n.getChecked()){
pot += n.fire()*weight.get(input.indexOf(n));
} else {
pot += n.getOut()*weight.get(input.indexOf(n));
} // end of condition (checked)
} // end of loop (for input)
} // end of condition (input exists)
checked = true;
pot -= bias;
pot += sense;
out = actFunc(pot);
return out;
} // end of fire()
// getting properties
public float getPot(){return pot;}
public boolean getChecked(){return checked;}
public float getOut(){return out;}
// setting properties
public void stimulate(float f){sense = f;}
public void setBias(float b){bias = b;}
public void setChecked(boolean c){checked = c;}
public void setOut(float o){out = o;}
// connection
public void connect(Neuron n, float w){
input.add(n);
weight.add(w);
}
public void deconnect(Neuron n){
weight.remove(input.indexOf(n));
input.remove(n);
}
// activation function
private float actFunc(float x){
if (x < 0) {
return 0f;
} else {
return 1f;
}
}
// constructor
public Neuron(Neuron[] ns, float[] ws, float b, float o){
if (ns != null){
input = new ArrayList<Neuron>();
weight = new ArrayList<Float>();
for (Neuron n : ns) input.add(n);
for (int i = 0; i < ws.length; i++) weight.add(ws[i]);
} else {
input = null;
weight = null;
}
bias = b;
out = o;
}
public Neuron(Neuron[] ns){
if (ns != null){
input = new ArrayList<Neuron>();
weight = new ArrayList<Float>();
for (Neuron n : ns) input.add(n);
for (int i = 0; i < input.size(); i++) weight.add((float)Math.random()*2f-1f);
} else {
input = null;
weight = null;
}
bias = (float)Math.random();
out = (float)Math.random();
}
}
First, define interface of any activation function:
public interface ActivationFunction {
float get(float f);
}
Then write some implementations:
public class StepFunction implements ActivationFunction {
#Override
public float get() {return (x < 0) ? 0f : 1f;}
}
public class SigmoidFunction implements ActivationFunction {
#Override
public float get() {return StrictMath.tanh(h);}
}
Finally, set some implementation to your Neuron:
public class Neuron {
private final ActivationFunction actFunc;
// other fields...
public Neuron(ActivationFunction actFunc) {
this.actFunc = actFunc;
}
public float fire(){
// ...
out = actFunc.get(pot);
return out;
}
}
as following:
Neuron n = new Neuron(new SigmoidFunction());
Note, neural netoworks are using signal propagation through neurons, where weights are produced. Computing of weight depends also on first derivative of an activation function. Therefore, I would extend ActivationFunction by method, which will return first derivative at specified point x:
public interface ActivationFunction {
float get(float f);
float firstDerivative(float x);
}
So the implemenations will look like:
public class StepFunction implements ActivationFunction {
#Override
public float get(float x) {return (x < 0) ? 0f : 1f;}
#Override
public float firstDerivative(float x) {return 1;}
}
public class SigmoidFunction implements ActivationFunction {
#Override
public float get(float x) {return StrictMath.tanh(x);}
// derivative_of tanh(x) = (4*e^(2x))/(e^(2x) + 1)^2 == 1-tanh(x)^2
#Override
public float firstDerivative(float x) {return 1 - Math.pow(StrictMath.tanh(x), 2);}
}
Then, use actFunction.firstDerivative(x); in fire() method where weight is being computed.
I want to use a map in Groovy where the keys will be instances of an unmutable class.
This is something I do often in Java and it works fine, like in this example class:
public class TestMap {
static final class Point {
final int x; final int y;
public Point(int x, int y) {this.x = x;this.y = y;}
}
public static void main(String[] args) {
Map<Point, String> map = new HashMap<>();
final Point origin = new Point(0, 0);
map.put(origin, "hello world !" );
if(!map.containsKey(origin))
throw new RuntimeException("can't find key origin in the map");
if(!map.containsKey(new Point(0,0))) {
throw new RuntimeException("can't find new key(0,0) in the map");
}
}
}
But when I try to achieve the same thing with Groovy, it doesn't work.
Why ?
Here is a sample non working example in Groovy:
class Point {
final int x; final int y
Point(int x, int y) { this.x = x; this.y = y }
public String toString() { return "{x=$x, y=$y}" }
}
def origin = new Point(0, 0)
def map = [(origin): "hello"]
map[(new Point(1,1))] = "world"
map.put(new Point(2,2), "!")
assert map.containsKey(origin) // this works: when it's the same ref
assert map.containsKey(new Point(0,0))
assert map.containsKey(new Point(1,1))
assert map.containsKey(new Point(2,2))
assert !map.containsKey(new Point(3,3))
You need to have an equals and hashCode method on your Point class so that the instances can be found as keys in the HashMap
You can do this quickly by adding an annotation in Groovy:
import groovy.transform.*
#EqualsAndHashCode
class Point {
final int x; final int y
Point(int x, int y) { this.x = x; this.y = y }
public String toString() { return "{x=$x, y=$y}" }
}
I have this sparse matrix implementation:
I'm trying to write getter/setter methods for individual elements based on their key, but I'm not sure how to do this with my custom type Coordinates. For example, theMatrix.get(coordinates) (the usual way) doesn't work.
Could someone show me how to do this?
Class coordinate is not accessible outside of your Matrix class.
Indeed, its an implementation detail that you don't want to make visible to the end-user. Please check the getters and setters in the example below.
If you still want to make Coordinates class available to the end-user, you wan make it public.
public class Matrix
{
private static class Coordinates
{
private int x = 0;
private int y = 0;
private int data = 0;
public Coordinates(final int x, final int y)
{
this.x = x;
this.y = y;
data = ((x + "") + (y + "")).hashCode();
}
#Override
public boolean equals(final Object obj)
{
if (obj instanceof Coordinates)
{
Coordinates Coordinates = (Coordinates) obj;
return ((x == Coordinates.x) && (y == Coordinates.y));
}
else
{
return false;
}
}
#Override
public int hashCode()
{
return data;
}
}
private int numrows;
private int numcolumns;
private HashMap<Coordinates, Double> theMatrix;
public Matrix(final int numrows, final int numcolumns)
{
this.numrows = numrows;
this.numcolumns = numcolumns;
}
public Matrix(HashMap<Coordinates, Double> matrixdata)
{
theMatrix = new HashMap<Coordinates, Double>(matrixdata);
}
public Double get(int row, int col, double defaultValue)
{
Double ret = theMatrix.get(new Coordinates(row, col));
return ret != null ? ret : defaultValue;
}
public void set(int row, int col, Double value)
{
theMatrix.put(new Coordinates(row, col), value);
}
}
I have really straight forward code, I am hoping that my issue is that I have just been looking at it too long. I am testing some calculations to make sure I am doing it right before I throw in a huge list. All I want to do is create a new objects through a for loop and toss them in my constructed array.
Contents of public static void main(String args[]) in my Main class:
PositionHolder[] positions = new PositionHolder[8];
PositionHolder currPosition;
int currPos = 0;
for(int i = 0; i <= 7; i++){
/* For Random Points */
currPosition = new PositionHolder(i);
System.out.println("Resetting " + i);
positions[i] = currPosition;
//positions[i].setxPos(100 * Math.random()); // these get set in the
//positions[i].setyPos(100 * Math.random()); // PositionHolder constructor
for(int k = i; k >= 0; k--){
System.out.println(k + ": " + positions[k].getxPos() + ", " + positions[k].getyPos());
}
}
Just for clarification, my PositionHolder class is as follows:
public class PositionHolder {
private static double xPos;
private static double yPos;
private static int point;
private static boolean visited;
public PositionHolder(int pointNumber){
setxPos(100 * Math.random());
setyPos(-100 * Math.random());
setPoint(pointNumber);
setVisited(false);
}
public double getxPos() {
return xPos;
}
public void setxPos(double xPos) {
PositionHolder.xPos = xPos;
}
public double getyPos() {
return yPos;
}
public void setyPos(double yPos) {
PositionHolder.yPos = yPos;
}
public int getPoint() {
return point;
}
public void setPoint(int point) {
PositionHolder.point = point;
}
public boolean isVisited() {
return visited;
}
public void setVisited(boolean visited) {
PositionHolder.visited = visited;
}
}
The problem is that for some reason each time through the for loop override the previous PositionHolders I have put in my array. As a quick example, here is the first few lines of my system output from the System.println towards the end of the for loop:
Resetting 0
0: 60.697435147416186, -96.35236848097432
Resetting 1
1: 57.98340997157546, -52.56948459757237
0: 57.98340997157546, -52.56948459757237
Resetting 2
2: 45.75236962694197, -32.03840605394901
1: 45.75236962694197, -32.03840605394901
0: 45.75236962694197, -32.03840605394901
So where I want 0 to stay at 60.69743.... and 1 to stay at 57.98340.... they are all getting set to the same (most resent) value. I wish I could say it is more complex than that, but that is it. What is going on?
--- The Answer, given below by Logan Murphy, is correct ---
As a note, not only should you take a break from time to time to avoid silly mistakes from code you have looked at too much, but you REALLY shouldn't rely on eclipses "fix" solutions to make good code :P
Because you set your variables to be static (shared between instances of the class). They need to be non-static like so
public class PositionHolder {
private double xPos;
private double yPos;
private int point;
private boolean visited;
public PositionHolder(int pointNumber){
setxPos(100 * Math.random());
setyPos(-100 * Math.random());
setPoint(pointNumber);
setVisited(false);
}
public double getxPos() {
return xPos;
}
public void setxPos(double xPos) {
this.xPos = xPos;
}
public double getyPos() {
return yPos;
}
public void setyPos(double yPos) {
this.yPos = yPos;
}
public int getPoint() {
return point;
}
public void setPoint(int point) {
this.point = point;
}
public boolean isVisited() {
return visited;
}
public void setVisited(boolean visited) {
this.visited = visited;
}
}
This way each instance of the class PositionHolder has its own variables (instance variables are globally declared variables that are non-static)