How can I create a program in Java that is able to alter its own source code, or a mathematical function that it is then to run?

StackOverflow https://stackoverflow.com/questions/20403161

Question

I want to create a program that uses an stochastic optimization algorithm to evolve mathematical functions, taking two constant numbers as inputs and evolving a function in order to produce a specific answer from those two numbers.

So say the inputs are 4 and 7, and I want the answer to be 230, the program would generate a function that produces this answer from the original inputs.

I'm capable of producing evolutionary algorithms, but I'm just not sure how to store the function information, randomly mutate it, and also allow that mutated function to be executed by the java program. Is this what is called meta programming? Is it possible in java? I know I can store constants that might be used in the function as variables. Thats easy. But how could I store operators, and functions such as sine cosine and tan, as variables that can be changed?

Was it helpful?

Solution

Please, dont alter the programs sourcecode and recompile at runtime.

There are tons of ways to evaluate functions, some are:

You should store the equation in a tree (done for you by many libraries), alter that tree in your genetic algorithm, and evaluate it.

You can store functions easily via interfaces or subclasses... It would be even easier with reflection.

But: You might find more efficient ways to determine that function. We can help you more if you give us the function the program should create.

OTHER TIPS

This might help

You can create "real" plugins with java. This thread talks about it:

How can I write my own plugin loader in java?

Basically, create a main program that allows you to compose and execute chains of plugins. Where plugins are your functions like sin, cos... Since you can load real plugins on the fly; you can create new random plugins and add them to your chain.

Generally Java does not support meta programming. But This will help you.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top