From 0a07b8c73f0166571fb402ba730d4db4f43bd523 Mon Sep 17 00:00:00 2001 From: Ben Ruijl Date: Fri, 17 Jul 2020 15:29:45 +0200 Subject: [PATCH] Fixes for #Optimize when bracketing - Fixes #7 - Make sure iranf(0) does not do mod 0 --- sources/optimize.cc | 16 ++++++++++++---- sources/reken.c | 1 + 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/sources/optimize.cc b/sources/optimize.cc index 4cdfdd5e..35822361 100644 --- a/sources/optimize.cc +++ b/sources/optimize.cc @@ -293,7 +293,7 @@ vector > get_brackets () { vector > brackets; if (has_brackets) { - int exprlen=8; // we need potential space for an empty bracket + int exprlen=10; // we need potential space for an empty bracket for (WORD *t=optimize_expr; *t!=0; t+=*t) exprlen += *t; WORD *newexpr = (WORD *)Malloc1(exprlen*sizeof(WORD), "optimize newexpr"); @@ -1642,8 +1642,8 @@ vector simulated_annealing() { // create a valid state where FACTORSYMBOL/SEPARATESYMBOL remains first vector state = occurrence_order(optimize_expr, false); int startindex = 0; - if (state[0] == SEPARATESYMBOL || state[1] == FACTORSYMBOL) startindex++; - if (state[1] == FACTORSYMBOL) startindex++; + if ((state.size() > 0 && state[0] == SEPARATESYMBOL) || (state.size() > 1 && state[1] == FACTORSYMBOL)) startindex++; + if (state.size() > 1 && state[1] == FACTORSYMBOL) startindex++; my_random_shuffle(BHEAD state.begin() + startindex, state.end()); // start from random scheme @@ -1652,11 +1652,19 @@ vector simulated_annealing() { std::vector best = state; // best state int bestscore = curscore; + + if (startindex == state.size() || state.size() - startindex < 2) { + return best; + } for (int o = 0; o < AO.Optimize.saIter; o++) { int inda = iranf(BHEAD state.size() - startindex) + startindex; int indb = iranf(BHEAD state.size() - startindex) + startindex; + if (inda == indb) { + continue; + } + swap(state[inda], state[indb]); // swap works best for Horner vector tree = Horner_tree(optimize_expr, state); @@ -1874,7 +1882,7 @@ inline static void next_MCTS_scheme (PHEAD vector *porder, vector *p // if this a new node, create node and add children if (!select->finished && select->childs.size()==0) { tree_node new_node(select->var); - int sign = SGN(order.back()); + int sign = (order.size() == 0) ? 1 : SGN(order.back()); for (int i=0; i<(int)mcts_vars.size(); i++) if (!var_used.count(mcts_vars[i])) { new_node.childs.push_back(tree_node(sign*(mcts_vars[i]+1))); diff --git a/sources/reken.c b/sources/reken.c index 48cd9b14..60a7b25b 100644 --- a/sources/reken.c +++ b/sources/reken.c @@ -3811,6 +3811,7 @@ UWORD wranf(PHEAD0) UWORD iranf(PHEAD UWORD imax) { + if (imax < 2) return 0; UWORD i; ULONG x = (LONG)1 << BITSINWORD, xmax = x - x%imax; while ( ( i = wranf(BHEAD0) ) >= xmax ) {}