I need help in figuring out how to generate a random set of functions.
Such as: Sin(Cos(Average(x, y)))
OR : Cos(Tan(Sin(Sin(x)))
etc..
The code I've come up with thus far is as follows, but I'm pretty certain it's not correct:
public class Functions {
public static double randomFunctions(int maxDepth, double x, double y) {
int random ;
double value = 1.0 ;
if (maxDepth == 0) {
random = (int) (Math.random() * 5 + 1);
if (random == 1 || random == 2) {
return x ;
}
if (random == 3 || random == 4) {
return y ;
}
if (random == 5) {
return Math.random() * 2 - 1 ;
}
} else if (maxDepth != 0) {
random = (int) (Math.random() * 17 + 1) ;
if (random == 1 || random == 2 || random == 3) {
return Math.sin(Math.PI * randomFunctions(maxDepth-1, x, y)) ;
}
if (random == 4 || random == 5 || random == 6) {
return Math.cos(Math.PI * randomFunctions(maxDepth-1, x, y)) ;
}
if (random == 7 || random == 8 || random == 9) {
return (randomFunctions(maxDepth-1, x, y) + randomFunctions(maxDepth-1, x, y))/2.0 ;
}
if (random == 10 || random == 11 || random == 12) {
return (randomFunctions(maxDepth-1, x, y) + randomFunctions(maxDepth-1, x, y))/2.0 ;
}
if (random == 13 || random == 14) {
System.out.println(random);
return x ;
}
if (random == 15 || random == 16) {
return y ;
}
else {
return (Math.random() * 2 - 1);
}
}
System.out.println("Fail");
return 0.0 ;
}
Any help or advice you can give me would be greatly appreciated. I know Math.sin
& cos
etc accept Radian values, but I'm thinking there is something wrong structurally.
I would recommend using an array of functions, and then randomly choose functions from the array to call. To get you started, here is how you might declare your array:
// define a functional interface which we will use
public Interface MathFunction {
public double apply(double d);
}
// declare our array of functions, using three lambda functions to statically declare
// the array
MathFunction[] functions = {x -> {return Math.cos(x);},
x -> {return Math.sin(x);},
x -> {return Math.tan(x);}};
This will only work in Java 8. To do the same in Java 7, simply declare anonymous MathFunction classes like so:
class Cosine implements MathFunction {
@Override
public double apply(double d) {
return Math.cos(d);
}
}
Then, use these classes to create your array:
MathFunction[] functions = {new Cosine(), new Sine(), new Tangent()};
Putting it all together:
public static double randomFunctions(int maxDepth, double x, double y) {
MathFunction[] functions = {new Cosine(), new Sine(), new Tangent()};
int currX = x;
int currY = y;
// repeatedly apply functions to each value randomly
for (int i = 0; i < maxDepth; i++) {
Random r = new Random();
currX = r.nextInt(functions.length - 1);
currY = r.nextInt(functions.length - 1);
}
// randomly return one of the two numbers
Random r = newRandom();
if (r.nextBoolean()) {
return currX;
} else {
return currY;
}
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments