Exemplo n.º 1
0
/**
 * \brief Evaluates an operator from the tree obtained from the parsed
 *        expression.
 * \param result (out) The result of the evaluation.
 * \param op The operator to evaluate.
 * \param left_tree The tree built from the left operand.
 * \param right_tree The tree built from the right operand.
 * \return true if the expression has evaluated.
 */
bool bf::arithmetic_parser::evaluate_operator
( double& result, char op, tree_node const& left_tree,
  tree_node const& right_tree ) const
{
  double left;
  double right;

  if( !evaluate_tree( left, left_tree )
      || !evaluate_tree( right, right_tree ) )
    return false;

  switch( op )
    {
    case '+':
      result = left + right;
      return true;
    case '-':
      result = left - right;
      return true;
    case '*':
      result = left * right;
      return true;
    case '/':
      result = left / right;
      return true;
    default:
      CLAW_FAIL( std::string( "unknown operand: " ) + op );
    }

  return false;
} // arithmetic_parser::evaluate_operator()
Exemplo n.º 2
0
void evaluate_pop(population *pop) {
	int k;

#ifdef DEBUG
	print_individual ( pop->ind, stdout );
	app_eval_fitness ( pop->ind );
	exit(0);
#endif

	for (k = 0; k < pop->size; ++k) {
		if (pop->ind[k].evald != EVAL_CACHE_VALID) {
			population_No = k;
			app_eval_fitness((pop->ind) + k);
		}
	}
	if (generation_No != (generationSIZE - 1)) {
		optimal_in_generation[generation_No + 1] = 1000;
	}
	if (optimal_in_generation[generation_No]
			>= optimal_in_generation[generation_No - 1]) {
		same_optimal_count++;
	} else {
		same_optimal_count = 1;
	}
	if (same_optimal_count > 3) {
		//current_max_importance++;
		printf("Printing File");
		FILE *out_file = fopen("regress.asim", "w");
		if (out_file) {
			//output_stream_open( OUT_ERROR);
			int i;
			double v, dv, disp;
			float error = 0.0f;
			for (i = 0; i < fitness_cases; ++i) {
				g.x = app_fitness_cases[0][i];
				v =
						evaluate_tree(
								((pop->ind)
										+ optimal_index_in_generation[generation_No])->tr[0].data,
								0);
				dv = app_fitness_cases[1][i];
				disp = fabs(dv - v);
				error += disp;

			}
			error = error / fitness_cases;
			fprintf( out_file, 50, "%f", (float)g.x);
			fprintf( out_file, 50, " %f", (float) error);
			fprintf( out_file, 50, "\n");
			fclose(out_file);
		//	output_stream_close( OUT_ERROR);
			termination_override = 1;
		}
	}
	printf("Index: %d ERR : %f -Index %d Same : %i\n", generation_No,
			optimal_in_generation[generation_No],
			optimal_index_in_generation[generation_No], same_optimal_count);

}
Exemplo n.º 3
0
int main()
{
        int i;
        char buffer[101];
        struct math_node **stack;
        int stack_size;
        struct math_node *tree;

        // get string
        printf("Enter the postfix expression to be evaluated: ");
        fgets(buffer, 100, stdin);

        // stackify
        stack = stackify(buffer, &stack_size);
        // test stackify:
        // printf("stack_size:%i\n", stack_size);
        // for (i=0; i<stack_size; i++) {
        //         printf("%s\n", (*(stack + i))->op);
        // }

        // treeify
        tree = treeify(stack, &stack_size);

        // evaluate the tree
        int value;
        value = evaluate_tree(tree);
        printf("The tree evaluates to: %d\n", value);

        // print various forms
        char* exp;
        int length;
        length = 0;
        exp = getexp_prefix(tree, &length);
        printf("Prefix Notation:   %s\n", exp);
        free(exp);
        exp = 0;
        length = 0;
        exp = getexp_infix(tree, &length);
        printf("Infix Notation:    %s\n", exp);
        free(exp);
        exp = 0;
        length = 0;
        exp = getexp_postfix(tree, &length);
        printf("Postfix Notation:  %s\n", exp);
        free(exp);
        exp = 0;

        // cleanup
        tree_destructor(tree);
        free(stack);
        stack = 0;
        return 0;
}
Exemplo n.º 4
0
/**
 * \brief Evaluates an arithmetic expression.
 * \param result (out) The result of the evaluation.
 * \param expr The expression to parse.
 * \return true if the expression has been well parsed.
 */
bool bf::arithmetic_parser::evaluate( double& result, std::string expr ) const
{
  arithmetic_grammar grammar;
  iterator begin( expr.c_str(), expr.c_str() + expr.size() );
  iterator end;

  boost::spirit::classic::tree_parse_info<iterator, node_factory> info;

  info =
    boost::spirit::classic::ast_parse<node_factory>
    ( begin, end, grammar, boost::spirit::classic::space_p );

  if ( !info.match )
    return false;
  else
    return evaluate_tree( result, info.trees[0] );
} // arithmetic_parser::evaluate()
Exemplo n.º 5
0
int evaluate_tree(struct math_node *tree)
{
        if (!tree) { return 0; }
        int value;
        switch (*(tree->op)) {
        case '+':
                value = evaluate_tree(tree->left) +
                        evaluate_tree(tree->right);
                break;
        case '-':       // special; numbers can start with -!
                if (*(tree->op + 1) >= 48 && *(tree->op + 1) <= 57) {
                        value = atoi(tree->op);
                } else {
                        value = evaluate_tree(tree->left) -
                                evaluate_tree(tree->right);
                }
                break;
        case '%':
                value = evaluate_tree(tree->left) %
                        evaluate_tree(tree->right);
                break;
        case '/':
                value = evaluate_tree(tree->left) /
                        evaluate_tree(tree->right);
                break;
        case '&':
                value = evaluate_tree(tree->left) &
                        evaluate_tree(tree->right);
                break;
        case '^':
                value = evaluate_tree(tree->left) ^
                        evaluate_tree(tree->right);
                break;
        default:
                value = atoi(tree->op);
                break;
        }
        return value;
}
DATATYPE evaluate_tree_recurse ( lnode **l, int whichtree, farg msg )	  //
{
	 globaldata* g = get_globaldata();//get the lists

     farg arg[MAXARGS];
     int i;
     function *f = (**l).f;
     treeinfo savearg;


     /* step the traversal pointer forward, now that we've saved which
	    function we're at. */
     ++*l;

     switch ( f->type )
     {
        case TERM_NORM:
							//---------------------------------------------------------
							/* normal terminal:  just call the user code. */
							//APPCODE HJJ

							arg[0].t = (*l);
							arg[0].writeHead = msg.writeHead;
							return (f->code)(whichtree, arg, f->arity);//HJJM
							break;
        case TERM_ERC:
 							//---------------------------------------------------------
							/* ERC terminal:  traversal pointer points to ERC structure.
							pull the value out, and step the pointer forward. */
							return (*((*l)++)).d->d;
              break;
        case FUNC_DATA: 
	   					//---------------------------------------------------------
							//FUNC_DATA: first evaluate subtree, then evaluate parent node
							/* function (DATA type):  recursively evaluate each subtree,
							saving the values.  pass these values to the user code. */

							for ( i = 0; i < f->arity; ++i ) {
									 arg[i].d = evaluate_tree_recurse ( l, whichtree, msg );	//
							}
							return (f->code)(whichtree, arg, f->arity);
							break;
        case EVAL_DATA:
							//---------------------------------------------------------
							//EVAL_DATA: first evaluate subtree, then evaluate parent node
							//ADF style, pass the args to a tree and evaluate another tree

							/* evaluation token (DATA type):  first evaluate each child,
							saving the returned values.  these values will be returned
							by the appropriate ARG tokens in the called tree. */
							oprintf(OUT_SYS, 30,"EVAL_DATA \n");
							for ( i = 0; i < f->arity; ++i )
									 arg[i].d = evaluate_tree_recurse ( l, whichtree, msg );	  //

							/* the arguments are stored using three fields in the global
							tree_map.  we save whatever was in these three fields in
							local variables. */
							savearg.arguments = tree_map[f->evaltree].arguments;
							savearg.argtype = tree_map[f->evaltree].argtype;
							savearg.evaluatedfrom = tree_map[f->evaltree].evaluatedfrom;

							/** now we store the new values in the global structure. **/
							/* first, the argument list. */
							tree_map[f->evaltree].arguments = arg;
							/* next, the type of this eval token. */
							tree_map[f->evaltree].argtype = EVAL_DATA;
							/* now the tree number which we are currently evaluating.  this
							is necessary so that nested ADFs evaluate correctly -- we must
							remember where we are so that ARG tokens know which tree's
							arguments to look at. */
							tree_map[f->evaltree].evaluatedfrom = whichtree;

							/* finally call evaluate_tree to evaluate the target tree. */
							arg->d = evaluate_tree ( current_individual->tr[f->evaltree].data,
																			f->evaltree, msg );

							/* restore the old values in the global structure. */
							tree_map[f->evaltree].arguments = savearg.arguments;
							tree_map[f->evaltree].argtype = savearg.argtype;
							tree_map[f->evaltree].evaluatedfrom = savearg.evaluatedfrom;

							/* return the final value. */
							return arg->d;
							break;

        case FUNC_EXPR:		 /*   */
								//---------------------------------------------------------
								//APPCODE HJJ
								/* function (EXPR type):  save the address of each child tree,
								using the skip nodes to quickly move the traversal pointer
								past the child. pass writing heads for all children */
								arg[0].writeHead = msg.writeHead; //pass the modifiable site ID
								for ( i = 0; i < f->arity; ++i ) {
									arg[i].t = (*l+1);
									*l += (**l).s;
									++*l;
								}
								/* now pass this array of saved trees to the user code. */
								return (f->code)(whichtree, arg, f->arity);
								break;
				case EVAL_EXPR:		
								//---------------------------------------------------------
								/* evaluation token (EXPR type):  works just like the DATA
								type, only the saved arguments are tree address instead
								of values. */
								oprintf(OUT_SYS, 30,"EVAL_EXPR \n");

								for ( i = 0; i < f->arity; ++i )
								{
										arg[i].t = (*l+1);
										*l += (**l).s;
										++*l;
								}
								savearg.arguments = tree_map[f->evaltree].arguments;
								savearg.argtype = tree_map[f->evaltree].argtype;
								savearg.evaluatedfrom = tree_map[f->evaltree].evaluatedfrom;
								tree_map[f->evaltree].arguments = arg;
								tree_map[f->evaltree].argtype = EVAL_EXPR;
								tree_map[f->evaltree].evaluatedfrom = whichtree;
								arg->d = evaluate_tree ( current_individual->tr[f->evaltree].data,
														 f->evaltree, msg );
								tree_map[f->evaltree].arguments = savearg.arguments;
								tree_map[f->evaltree].argtype = savearg.argtype;
								tree_map[f->evaltree].evaluatedfrom = savearg.evaluatedfrom;
								return arg->d;
								break;
        case EVAL_TERM:
								//---------------------------------------------------------
								/* evaluation token (TERM type):  works just like the DATA
								type, only we pass NULL as an argument list. */
								oprintf(OUT_SYS, 30,"EVAL_TERM \n");

								savearg.arguments = tree_map[f->evaltree].arguments;
								savearg.argtype = tree_map[f->evaltree].argtype;
								savearg.evaluatedfrom = tree_map[f->evaltree].evaluatedfrom;
								tree_map[f->evaltree].arguments = NULL;
								tree_map[f->evaltree].argtype = EVAL_TERM;
								tree_map[f->evaltree].evaluatedfrom = whichtree;
								arg->d = evaluate_tree ( current_individual->tr[f->evaltree].data,
																	 f->evaltree, msg );
								tree_map[f->evaltree].arguments = savearg.arguments;
								tree_map[f->evaltree].argtype = savearg.argtype;
								tree_map[f->evaltree].evaluatedfrom = savearg.evaluatedfrom;
								return arg->d;
								break;
        case TERM_ARG:
								//---------------------------------------------------------
								/* an ARG terminal. */
								oprintf(OUT_SYS, 30,"TERM_ARG \n");
								if ( tree_map[whichtree].argtype == EVAL_DATA )
								/* if the EVAL token calling this tree is of type DATA, then
								just pull the value out of the argument list and return it. */
										 return tree_map[whichtree].arguments[f->evaltree].d;
								else
								/* if the EVAL token calling this tree is of type EXPR, then
								evaluate the tree pointer in the argument list and return
								the value. */
										 return evaluate_tree ( tree_map[whichtree].arguments[f->evaltree].t, 
													tree_map[whichtree].evaluatedfrom, msg );
								break;
     }
		 oprintf(OUT_SYS, 30,"evaluate_tree_recurse Ending...........\n");
		 return 0.0;
}
Exemplo n.º 7
0
Arquivo: tree.c Projeto: c0cky/pcc-3
int eval(EXPR node) {
	int nodeVal;

	// Check to see if we can return an already evaluated expr
	if (node->is_evaluated == 1 && node->is_line == 1) {
		if (node->tag == UNOP_EXPR) { // Always evaluate 
			if (node->u.unop.op != LINE_REF) { // a line reference
				return node->evaluated_val;
			}
		}
		else {
			if (node->tag != VAR_EXPR) { // Always evaluate a variable
				return node->evaluated_val;
			}
		}
	}

	if (node->tag == VAR_EXPR) {
		char alpha = node->u.var.name;
		nodeVal = get_val(alpha);
	}
	else if (node->tag == CONST_EXPR) {
		nodeVal = node->u.constant.val;
	}
	else if (node->tag == BINOP_EXPR) {
		int l = eval(node->u.binop.left_arg);
		int r =	eval(node->u.binop.right_arg);

		switch(node->u.binop.op) {
			case MINUS:
				nodeVal = l - r;
				break;
			case PLUS:
				nodeVal = l + r;
				break;
			case MULT:
				nodeVal = l * r;
				break;
			case DIV:
				nodeVal = l / r;
				break;
			case MOD:
				nodeVal = l % r;
				break;
		}
	}
	else if (node->tag == UNOP_EXPR) {
		int i = eval(node->u.unop.arg);

		switch(node->u.unop.op) {
			case UMINUS:
				nodeVal = -i;
				break;
			case LINE_REF:
				nodeVal = evaluate_tree(node->u.unop.arg);
				break;
		}
	}
	
	set_node_as_evaluated(node, nodeVal);
	
	return nodeVal;
}