Overview
The first step is initialization. That is, we need to create a population of randomly generated functions that will be evaulated against the data to see how close the function approximates the specified the values.
Randomly Generated AST's
The following function is designed to randomly select an AST with a possibly random set of arguments. Based on the result of a random number, it selects an AST from a list.
function generate(){
let rand = randomInteger(5);
if(rand === 0) return {
function:function(a,b){
return a+b;
},
name:'add',
arguments:[identity,randomConstant()]
}
else if(rand === 1) return {
function:function(a,b){
return a*b;
},
name:'multiply',
arguments:[identity,randomConstant()]
}
else if(rand === 2) return {
function:function(x){
return Math.sin(x);
},
name:'sine',
arguments:[identity]
}
else if(rand === 3) return {
function:function(x){
return Math.cos(x);
},
name:'cosine',
arguments:[identity]
}
else if(rand === 3) return {
function:function(x){
return Math.log(x);
},
name:'log',
arguments:[identity]
}
else return {
function:function(x){
return Math.exp(x)
},
name:'exp',
arguments:[identity]
}
}
const identity = {
function:function(x){
return x;
},
name:'identity'
};
function randomConstant(){
return 20*(Math.random()-0.5);
}
function randomInput(){
if(Math.random()<0.5) return randomConstant();
return identity;
}