Random numbers shared between canvases - java

I am new to Java, and I am also new to posting a question online. So please bear with me.
I am currently constructing a Java program which displays several canvases, and I require the different canvases to use shared and/or inherited information. Let's assume for simplicity that canvas C1 displays a polygon with random vertices on a circle. Currently these vertices are created in a coordinate class and are then instantiated by a drawing class. I am now trying to store these values in a way which allows the second canvas C2 (via drawing class) to use them, but without instantiating it, as I need the same sequence of random numbers.
Let this be a simplified example of my coordinate class:
public class Coord {
public Complex[] z = new Complex[5];
public Coord() {}
// create n random vertices (length of a and z will match)
public Complex[] randCoord(Complex[] a) {
for(int i = 0; i < a.length; i++){
z[i] = new Complex(200 * Math.random(), 200 * Math.random());
}
return z;
}
// public static Complex[] getCoord() {
// return z;
// }
}
The commented out section is one of my million attempts to generate a static version of the coordinate list, but I am not allowed to return z as it is not a static variable (in this case). I am probably missing something painfully obvious in regard to transferring between static and non-static methods, but any insight on how to store the random sequence (and likewise, how to call it) would be appreciated.

It sounds like the Singleton pattern would be helpful :
public class Coord {
private static final Complex[] z = fixedRandomPoints(5);
private Coord() {}
//this is the method you call from both canvases
public static Complex[] getInstance() {
return z;
}
private static Complex[] fixedRandomPoints(int n) {
final Complex[] results = new Complex[n];
for(int i = 0; i < n.length; i++){
results[i] = new Complex(200 * Math.random(), 200 * Math.random());
}
return results;
}
}
The only thing thats unclear is the relationship of this class to the 'a' variable, which I think you need to explain a little better.

First of all, you should read up on the MVC-pattern: Model-View-Controller.
Secondly, it looks like what you're currently trying to do can simply be done by declaring z to be static:
public static Complex[] z = new Complex[5];

Related

Finding all complex roots of cubic function by using Newton's Method in Java

I've looked everywhere for code I can understand which could help me on my way. I've found one but I'm struggling, so I hope someone could help me.
This is what I want to achieve:
Solve a cubic function (ax^3+bx^2+cx+d) where a,b,c and d are filled
in by the command line when you run it.
I need the roots and complex roots to be found using the Newton's Method. The code I'm struggling with is this, but I don't know if this works and I don't know how I can calculate all 3 roots (even knowing if it has multiplicity 1, 2 or 3).
Any help is appreciated.
import java.util.function.Function;
public class Newton {
static double a = Polynom.geta(); // these are to get the input from the class you run from calling this class to solve the roots
static double b = Polynom.getb();
static double c = Polynom.getc();
static double d = Polynom.getd();
public static void main(String args[]) {
}
private Complex[] sqrt(double x, double y) {
Complex com = new Complex(x,y); // Complex is my class that deals with Complexnumbers, com is supposed to get the value of the root in the end
double tolerance = 1e-11; // tolerance for the error
int iterations = 1, max = 512;
Complex aa = com.pow(3).multiply(a); // These put in the values from input to complex values and fill in the cubic function of ax^3+bx^2+cx+d
Complex bb = com.pow(2).multiply(b);
Complex cc = com.multiply(c);
Complex dd = com.pow(2).multiply(a).multiply(3.0);
Complex ee = com.multiply(2.0).add(com);
Complex function = aa.add(bb).add(cc).add(d,0);
Complex derivative = dd.add(ee);
for(int k = 0; k<3; k++) {
while(iterations<max) {
Complex difference = function.divide(derivative); //difference=fx/dx
com = com.subtract(difference);
if (Math.abs(difference.getReal()) < tolerance && Math.abs(difference.getImaginary()) < tolerance)
return com; // this is where i get an error atm "Cannot convert from Complex to Complex
iterations++;
}
}
}

Displaying arraylist of objects containing one attribute whose value is superior to a certain value

I am trying to display an arraylist of recordings for mountain climbing where the mountain height was superior to 5K.
I am invoking an object method getheight() from another class but every time I try to compile, I am told that double can't be dereferenced. what am I doing wrong here? is there a better way of displaying a arraylist of objects containing an attribute whose value is superior to a certain number in Java? I have a feeling that I am close but yet far off the target. any tips?
public void Displayrecording()
{
double highestheights;
for(int i=0; i< 5; i++)
if(highestheights.getheight() > 5)
{
System.out.print(records.get(i));
}
}
A double is just a number. It does not have a height, or anything else. It's just a number.
So all you need is highestheights > 5.
If getHeight is going to give you altitude it looks you're looking for something like:
public void Displayrecording()
{
double highestheights;
for(int i = 0; i < 5; i++) {
highestheights = /*maybe some static class here*/getheight(/*maybe some parameter here*/);
if(highestheights > 5000)
{
System.out.print(records.get(i));
}
}
}
Generally your code is missing an array with mountain names or ids.

Why can't these variables be resolved?

I need to write a program and, in one step of it, I need to construct a function that calculates the number of rabbits.
The problem is that Eclipse shows a message saying that the variable I created "cannot be resolved to a variable" and I don't understand why it happens. Can someone help me?
Here is part of my code
I am showing all my code because it would get bigger and it is not needed, in order to solve this problem
class Rabbits {
static int nbRabbits = initRabbits; // ERROR HERE!!!!!!!!!!!!!!!!!!!!!!!!!!
static int nbFoxes = initFoxes; // ERROR HERE!!!!!!!!!!!!!!!!!!!!!!!!!!
int rabbits = 0;
public static int calculateRabbits(int rabbits, int foxes, double AttackRate) {
for (int i = 0; i < Duration; ++i) {
rabbits = nbRabbits;
nbRabbits *= (1.0 + Rabbits_growth_rate - AttackRate * nbFoxes);
}
return nbRabbits;
}
public static void main(String[] args) {
Scanner keyb = new Scanner(System.in);
// Enter initial population
int initFoxes = enterPopulation("foxes", 2, keyb); //at least 2 foxes
int initRabbits = enterPopulation("rabbits", 5, keyb); //at least 5 rabbits
// SOME MORE CODE HERE
} // end main
} // end of class
initRabbits and initFoxes are variables entered by the user when I call enterPopulation method.
I'm new to Java and, unfortunately, I cannot change the logic of this code. For example, I cannot put the calculateRabbits method inside the main neither change the begin or the end of the code.
initRabbits only exists within the main method. That is it's scope.
You are attempting to statically reference something it can't see. You are attempting to populate nRabbits before a value for innitRabbits exists. This is impossible.
Your trying to assign a value to your nb variables from a variable that hasn't been created yet. Skip making four variables and just assign the nbs to 0 outside of your main class, then give them the value you want inside it. They will then retain that value outside of the main class and be visible.
static int nbRabbits = 0;
static int nbFoxes = 0;
//in main class
nbFoxes = enterPopulation("foxes", 2, keyb); //at least 2 foxes
nbRabbits = enterPopulation("rabbits", 5, keyb); //at least 5 rabbits

Fast interpolation between a collection of points

I've built a model of the solar system in Java. In order to determine the position of a planet it does do a whole lot of computations which give a very exact value. However I am often satisfied with the approximate position, if that could make it go faster. Because I'm using it in a simulation speed is important, as the position of the planet will be requested millions of times.
Currently I try to cache the position of a planet throughout its orbit and then use those coordinates over and over. If a position in between two values is requested I perform a linear interpolation. This is how I store values:
for(int t=0; t<tp; t++) {
listCoordinates[t]=super.coordinates(ti+t);
}
interpolator = new PlanetOrbit(listCoordinates,tp);
PlanetOrbit has the interpolation code:
package cometsim;
import org.apache.commons.math3.util.FastMath;
public class PlanetOrbit {
final double[][] coordinates;
double tp;
public PlanetOrbit(double[][] coordinates, double tp) {
this.coordinates = coordinates;
this.tp = tp;
}
public double[] coordinates(double julian) {
double T = julian % FastMath.floor(tp);
if(coordinates.length == 1 || coordinates.length == 0) return coordinates[0];
if(FastMath.round(T) == T) return coordinates[(int) T];
int floor = (int) FastMath.floor(T);
if(floor>=coordinates.length) floor=coordinates.length-5;
double[] f = coordinates[floor];
double[] c = coordinates[floor+1];
double[] retval = f;
retval[0] += (T-FastMath.floor(T))*(c[0]-f[0]);
retval[1] += (T-FastMath.floor(T))*(c[1]-f[1]);
retval[2] += (T-FastMath.floor(T))*(c[2]-f[2]);
return retval;
}
}
You can think of FastMath as Math but faster. However, this code is not much of a speed improvement over calculating the exact value every time. Do you have any ideas for how to make it faster?
There are a few issues I can see, the main ones I can see are as follows
PlanetOrbit#coordinates seems to actually change the values in the variable coordinates. As this method is supposed to only interpolate I expect that your orbit will actually corrupt slightly everytime you run though it (because it is a linear interpolation the orbit will actually degrade towards its centre).
You do the same thing several times, most clearly T-FastMath.floor(T) occures 3 seperate times in the code.
Not a question of efficiency or accuracy but the variable and method names are very opaque, use real words for variable names.
My proposed method would be as follows
public double[] getInterpolatedCoordinates(double julian){ //julian calendar? This variable name needs to be something else, like day, or time, or whatever it actually means
int startIndex=(int)julian;
int endIndex=(startIndex+1>=coordinates.length?1:startIndex+1); //wrap around
double nonIntegerPortion=julian-startIndex;
double[] start = coordinates[startIndex];
double[] end = coordinates[endIndex];
double[] returnPosition= new double[3];
for(int i=0;i< start.length;i++){
returnPosition[i]=start[i]*(1-nonIntegerPortion)+end[i]*nonIntegerPortion;
}
return returnPosition;
}
This avoids corrupting the coordinates array and avoids repeating the same floor several times (1-nonIntegerPortion is still done several times and could be removed if needs be but I expect profiling will show it isn't significant). However, it does create a new double[] each time which may be inefficient if you only need the array temporarily. This can be corrected using a store object (an object you used previously but no longer need, usually from the previous loop)
public double[] getInterpolatedCoordinates(double julian, double[] store){
int startIndex=(int)julian;
int endIndex=(startIndex+1>=coordinates.length?1:startIndex+1); //wrap around
double nonIntegerPortion=julian-startIndex;
double[] start = coordinates[startIndex];
double[] end = coordinates[endIndex];
double[] returnPosition= store;
for(int i=0;i< start.length;i++){
returnPosition[i]=start[i]*(1-nonIntegerPortion)+end[i]*nonIntegerPortion;
}
return returnPosition; //store is returned
}

Java OOP triangle existence

I have recently started with programming. So far I have learned basics and now its time for OOP and so i have some questions as im building basic programs to just understand principals and link to way I would use it in practical ways.
So I am making simple triangle program in Java, so far it calculates perimeter (later will ad other shapes and other parameters), I hit the wall where I want to add Triangle existence (as side can't be negative) and also Id like to allow user input. Thing is i don't know where to put code and how to refer to class. Linear (non OOP) way it is simple, but how its done in OOP, do i have to make another class or in Triangle class via methods?
my code:
public class Trissturis {
private int sideA, sideB, sideC;
private double perimeter;
public Trissturis(int a, int b, int c) {
sideA = a;
sideB = b;
sideC = c;
}
public double getPerimeter() {
return sideA + sideB + sideC;
}
}
public class TestTri {
public static void main(String[] args) {
Trissturis t1 = new Trissturis(10, 20, 30);
System.out.println("perimeter is " + t1.getPerimeter());
Trissturis t2 = new Trissturis(-1, 20, 30);
}
}
To validate the triangle you have to check that all sides have a length greater than zero, and that no side is longer than the sum of the other two. An method that would accomplish this is:
public boolean isValid(){
return (sideA>0)&&(sideB>0)&&(sideC>0)&&(sideA+sideB>sideC)&&(sideA+sideC>sideB)&&(sideC+sideB>sideA);
}
For the user to input values, it is better to have separate user-interface classes. If this will be a desktop application, you could use some of the Swing classes, for example (although there are alternatives).
interface TriangleFactory {
Triangle create();
}
class ConsoleTriangleFactory implements TriangleFactory {
#Override
Triangle create() {
// read perimeter from console here with some nice prompt
// check that every side is > 0,
// if it's not a number or less than 0 - then do some alert
}
}
Your code to check that the triangle is constructed correctly (with non-negative values, etc) belongs in the Triangle class.
Code to take user input can go in main() in your Test for a small program, but could go in a separate UI namespace for a larger application.
hth

Categories

Resources