#include #include #include #include #include #include #include "dynamic-array.h" // fGold(x1,x2) = [ 1 + ( x1 + x2 + 1)^2 * (19 - 14*x1 + 3*x1^2 - 14*x2 + 6*x1*x2 + 3*x2^2)] * // [30 + (2*x1 - 3*x2 )^2 * (18 - 32*x1 + 12*x1^2 + 48*x2 - 36*x1*x2 + 27*x2^2)] // -2 <= xi <= +2, i = 1:2 #define FUNCTIONS \ FUNCTION (ADD, "+", l + r ) \ FUNCTION (SUB, "-", l - r ) \ FUNCTION (MUL, "*", l * r ) \ FUNCTION (DIV, "/", l / r ) \ FUNCTION (ABS_LEFT, "abs", fabs (l)) \ FUNCTION (ABS_RIGHT, "abs", fabs (r)) \ FUNCTION (SIN_LEFT, "sin", sinf (l)) \ FUNCTION (SIN_RIGHT, "sin", sinf (r)) \ FUNCTION (COS_LEFT, "cos", cosf (l)) \ FUNCTION (COS_RIGHT, "cos", cosf (r)) \ FUNCTION (EXP_LEFT, "exp", expf (l)) \ FUNCTION (EXP_RIGHT, "exp", expf (r)) #define FUNCTION(SYM, STR, EXP) FUNCTION_##SYM, enum function { FUNCTIONS FUNCTION_COUNT }; #undef FUNCTION #define FUNCTION(SYM, STR, EXP) [FUNCTION_##SYM] = STR, const char *function_strs[] = { FUNCTIONS }; #undef FUNCTION union uif { unsigned int u; float f; }; #define FUNCTION__SYM_TO_NAN(SYM) ((union uif) ((SYM) << 1 | 0xFFE00001)).f #define FUNCTION__NAN_TO_SYM(NAN) ((((union uif) (NAN)).u & 0x001FFFFE) >> 1) #define FUNCTION__NAN_TO_STR(NAN) function_strs[FUNCTION__NAN_TO_SYM (NAN)] #define TREE_DEPTH 4 #define NODE_COUNT ((2 << TREE_DEPTH - 1) - 1) float tree[NODE_COUNT]; void print_tree (float tree[NODE_COUNT], const char *filename) { const char *ext = strchr (filename, '.'); if (!ext) return; char *command; asprintf (&command, "dot -T%s -o %s", ext + 1, filename); FILE *dot = popen (command, "w"); // FILE *dot = fopen ("dump.dot", "w"); free (command); fprintf (dot, "digraph G {\n"); int stack[TREE_DEPTH] = { TREE_DEPTH }; int top = 1; for (int i = 0; i < NODE_COUNT; ++i) { if (isnan (tree[i])) fprintf (dot, " n%d [label=\"%d: %s\"];\n", i, i, FUNCTION__NAN_TO_STR (tree[i])); else fprintf (dot, " n%d [label=\"%d: %f\"];\n", i, i, tree[i]); int depth = stack[--top]; if (depth == 1) continue; // leaf stack[top++] = depth - 1; stack[top++] = depth - 1; int left = i + 1; int right = i + ((1 << depth - 1)); fprintf (dot, " n%d -> n%d;\n", i, left); fprintf (dot, " n%d -> n%d;\n", i, right); } fprintf (dot, "}\n"); pclose (dot); } int main (int argc, char *argv[]) { srand (time (NULL)); printf ("node_count: %d\n", NODE_COUNT); for (int i = 0; i < NODE_COUNT; ++i) { if (rand () % 2) tree[i] = rand () /(float) RAND_MAX; else tree[i] = FUNCTION__SYM_TO_NAN (rand () % FUNCTION_COUNT); } print_tree (tree, "tree.svg"); return EXIT_SUCCESS; }