void Simplex::Initialize()
{
    // calcola l, h
    int l = 0;
    int h = 0;

    double val_l = EvalFunction(m_P[0]);
    double val_h = EvalFunction(m_P[0]);

    double val_curr;

    for (int i = 1; i < 3; i++)
    {
        val_curr = EvalFunction(m_P[i]);

        if (val_curr < val_l)
        {
            l = i;
            val_l = val_curr;
        }

        else if (val_curr > val_h)
        {
            h = i;
            val_h = val_curr;
        }
    }

    m_l = l;
    m_h = h;

    // calcola la centroide m_Pbar
    double x_c = 0;
    double y_c = 0;

    for (int i = 0; i < 3; i++)
    {
        if (i != h)
        {
            x_c = x_c + m_P[i] -> GetX();
            y_c = y_c + m_P[i] -> GetY();
        }
    }

    m_Pbar -> SetPoint(0.5*x_c, 0.5*y_c);

    return;

}
bool Simplex::TerminatingCondition()
{
    double sum = 0;
    double val = 0;
    for (int i = 0; i < 3; i++)
    {
        val = EvalFunction(m_P[i]) - EvalFunction(m_Pbar);
        sum = sum + val*val;
    }

    if (sqrt(sum/3.) < 1.e-8)
    {return true;}

    else
    {return false;}
}
예제 #3
0
TCHAR * EVAL::EvalFactor(TCHAR * pExpr, double * pValue, INT * pError)
{
	EVAL_EAT_WHITE( pExpr );

	if     ( * pExpr == '\0'  ) return pExpr;
	else if( isdigit(* pExpr) ) return EvalConstant( pExpr, pValue, pError );
	else if( * pExpr == '('   ) return EvalParentheses( pExpr, pValue, pError );
	else if( * pExpr == '$'   ) return EvalVariable( pExpr, pValue, pError );
	else if( isalpha(* pExpr) ) return EvalFunction( pExpr, pValue, pError );
	else   /* other cases    */ { * pError = EVAL_ERROR_WRONG_SYNTAX; return pExpr; }
}
예제 #4
0
TCHAR * EVAL::EvalFunction(TCHAR * pExpr, double * pValue, INT * pError)
{
	EVAL_EAT_WHITE( pExpr );

	TCHAR * pEnd = pExpr;
	while( isalnum(* pEnd) ) pEnd++;

	TCHAR szFun[2048]; INT nLen = pEnd - pExpr;
	if( nLen > 0 ) { strncpy( szFun, pExpr, nLen ); szFun[nLen] = '\0'; strlwr(szFun); }
	else { * pError = EVAL_ERROR_WRONG_SYNTAX; return pExpr; }

	INT nFunction;
	if( hashFunctions.Lookup( szFun, nFunction ) ) { pExpr = pEnd; }
	else { * pError = EVAL_ERROR_FUNCTION_NOT_DEFINED; return pExpr; }


	INT argc = 0; double argv[EVAL_MAX_ARGUMENT_COUNT];

	EVAL_EAT_WHITE( pExpr );
	if( * pExpr == '(' ) pExpr++; // skip '('
	else { * pError = EVAL_ERROR_WRONG_SYNTAX; return pExpr; }

	EVAL_EAT_WHITE( pExpr );
	if( * pExpr != ')' ) { // not a void parameter function
		pExpr = EvalExpression( pExpr, & (argv[argc++]), pError );
		if( * pError ) return pExpr;
	}

	EVAL_EAT_WHITE( pExpr );
	TCHAR op = * pExpr;

	while( op == ',' ) {
		pExpr++; // skip commma operator

		EVAL_EAT_WHITE( pExpr );
		pExpr = EvalExpression( pExpr, & (argv[argc++]), pError );
		if( * pError ) return pExpr;

		EVAL_EAT_WHITE( pExpr );
		op = * pExpr;
	}

	EVAL_EAT_WHITE( pExpr );
	if( * pExpr == ')' ) pExpr++; // skip ')'
	else { * pError = EVAL_ERROR_WRONG_SYNTAX; return pExpr; }

	if( EvalFunction( nFunction, argc, argv, pValue ) ) { }
	else { * pError = EVAL_ERROR_FUNCTION_ARGUMENT_COUNT; return pExpr; }

	return pExpr;
}
예제 #5
0
파일: eval.c 프로젝트: fetastein/scheme
Expr* EvalPair(Env* env, Expr* expr, Expr* cont){
    expr = expr->u.list;
    //  expr=expr->next;
  if(strcmp(expr->u.symbol, "+") == 0){
    return EvalPlus(env, expr, cont);
  }else if(strcmp(expr->u.symbol, "-") == 0){
    return EvalMinus(env, expr, cont);
  }else if(strcmp(expr->u.symbol, "*") == 0){
    return EvalMul(env, expr, cont);
  }else if(strcmp(expr->u.symbol, "define") == 0){
    return EvalDefine(env, expr, cont);
  }else if(strcmp(expr->u.symbol, "if") == 0){
    return EvalIf(env, expr, cont); 
  }else if(strcmp(expr->u.symbol, "lambda") == 0){
    return EvalLambda(env, expr, cont);
  }else if(strcmp(expr->u.symbol, "halt") == 0){
    //    return expr; // return Halt expression.
    return Eval(env, GetSecond(expr), cont);
  }else if(strcmp(expr->u.symbol, "car") == 0){
    return EvalCar(env, expr, cont);
  }else if(strcmp(expr->u.symbol, "cdr") == 0){
    return EvalCdr(env, expr, cont);
  }else if(strcmp(expr->u.symbol, "null?") == 0){
    return EvalNullp(env, expr, cont);
  }else if(strcmp(expr->u.symbol, "pair?") == 0){
    return EvalPairp(env, expr, cont);
  }else if(strcmp(expr->u.symbol, "list")== 0){
    //    puts("to EvalList");
    Expr* ret = EvalList(env, expr, cont);
    //    puts("from EvalList");
    return ret;
  }else if(strcmp(expr->u.symbol, "let") == 0){
    puts("go let");
    return EvalLet(env, expr, cont);
  }else if(strcmp(expr->u.symbol, "cons") == 0){
    return EvalCons(env ,expr, cont);
  }else if(strcmp(expr->u.symbol, "append") == 0){
    return EvalAppend(env, expr, cont);
  }else if(strcmp(expr->u.symbol, ">") == 0){
    return EvalGT(env, expr, cont);
  }else{
    //    puts("Eval Function");
    char* funcname = expr->u.symbol;
    //    printf("funcname is %s\n", funcname);
    Expr* ret =  EvalFunction(env, expr,  cont);
    return ret;
    //    printf("funcname %s end\n", funcname);
  }
}
void Simplex::OneCall()
{
    // calcola l,h e centroide
    Initialize();

    Reflection();

    double ystar = EvalFunction(m_Pstar);
    double y_l = EvalFunction(m_P[m_l]);
    double y_h = EvalFunction(m_P[m_h]);

    // il punto riflesso sta sotto y_l
    if (ystar < y_l)
    {
        Expansion();

        // espansione riuscita
        if (EvalFunction(m_Pstarstar) < y_l)
        {
            m_P[m_h]->SetPoint(m_Pstarstar);
            return;
        }

        // espansione fallita
        else
        {
            m_P[m_h]->SetPoint(m_Pstar);
            return;
        }
     }

    // il punto riflesso non sta sotto y_l
    else
    {
        // calcola se il punto riflesso è maggiore di tutti gli altri
        int counter = 0;
        for (int i = 0; i < 3; i++)
        {
            if ( ystar > EvalFunction(m_P[i]) )
            {counter++;}
        }

        // il punto non è maggiore di tutti gli i != h
        if (counter < 2)
        {
            m_P[m_h]->SetPoint(m_Pstar);
            return;
        }

        // il punto è maggiore di tutti gli i (!)= h
        else
        {
            // se non è maggiore di h, sostituisco h
            if (counter < 3)
            {
                m_P[m_h]->SetPoint(m_Pstar);
                y_h = EvalFunction(m_P[m_h]);
            }

            Contraction();

            // il punto contratto non è maggiore di y_h
            if (EvalFunction(m_Pstarstar) <= y_h)
            {
                m_P[m_h]->SetPoint(m_Pstarstar);
                return;
            }
            // il punto contratto è maggiore di y_h
            else
            {
                double x_point_l = m_P[m_l]->GetX();
                double y_point_l = m_P[m_l]->GetY();
                for (int i = 0; i < 3; i++)
                {
                    m_P[i]->SetX(0.5*(m_P[i]->GetX() + x_point_l));
                    m_P[i]->SetY(0.5*(m_P[i]->GetY() + y_point_l));
                }
                return;
            }
        }
   }

}
예제 #7
0
char Parse (struct Variable *Vars) {	// grabs first two tokens to see if they are an assign statment
	// Symbol-specified functions:
	//		= (Assign), + (Add), - (Subtract), * (Multiply), / (Divide), % (Modulus), ^ (Power)
	// Future symbols: ! (Factorial / Gamma function), 
	// Unused symbols: ~, `, @, #, $, &, [, ], {, }, |, \, ;, :, ', ", ?, ,, <, >,
	line_index = 0;
	char look = 0, status = 0;
	
	printf ("> ");
	fflush (0);
	
	struct TokenStruct /*Oper*/and = NextToken (&look);
	
	// check for calculator commands
	if (!strcmp (and.Token, "DISPLAY")) {	// display variable tree
		char *disp = 0;
		DisplayVars (Vars, disp, 0);
		HandleError (and, 0, &look);
		return 0;
	}
	else if (!strcmp (and.Token, "ECHO")) {	// toggle input echo mode
		ECHO = 1 - ECHO;
		if (ECHO) { puts ("Input echo on"); } else { puts ("Input echo off"); }
		HandleError (and, 0, &look);
		return 0;
	}
	else if (!strcmp (and.Token, "HELP")) {	// display help screen
		puts ("Basic Calculator V 0.9");
		puts ("--------------------------------------------------------------------------------");
		puts ("This program is meant to be used as a general purpose calculator, akin to bc. Users can input arithmitic expressions of arbitrary length, assign and retrieve variables, and calculate common math functions. If the expression input isn't valid, the program displays an error message, indicates where in the line the problem occured, clears the input and resumes operation. In addition, users can work in interactive mode or redirect input scripts to execute a list of operations.");
		puts ("--------------------------------------------------------------------------------");
		puts ("COMMANDS: (case sensitive)");
		puts ("	DISPLAY	:	Display defined variables and their associated values.");
		puts ("	ECHO	:	Echo user input on next line. Useful when using an input script."); 
		puts ("	HELP	:	Display this help screen.");
		puts ("	QUIT	:	Quit this calculator program.");
		puts ("--------------------------------------------------------------------------------");
		puts ("MATH FUNCTIONS: (not case sensitive)\n");
		puts ("ABS / ABSOLUTE	:\n	return the absolute value of the argument. Accepts one argument.");
		puts ("ASIN / ARCSINE	:\n	return the arc sine (inverse sine function) of the argument. Accepts one argument.");
		puts ("ACOS / ARCCOSINE	:\n	return the arc cosine (inverse cosine function) of the argument. Accepts one argument.");
		puts ("ATAN / ARCTANGENT	:\n	return the arc tangent (inverse tangent function) of the argument. Accepts one argument.");
		puts ("COS / COSINE	:\n	return the cosine of the argument. Accepts one argument.");
		puts ("DIST / DISTANCE / HYPOTENUSE	:\n	return the pythangorian distance (hypotenuse) between two values. Accepts two arguments.");
		puts ("E	:\n	return the value of e. Accepts no arguments.");
		puts ("EXP	:\n	return the exponent of the argument (e ^ arg). Accepts one argument.");
		puts ("LN / NATURAL_LOG	:\n	return the natural log of the argument (arg = e ^ x). Accepts one argument.");
		puts ("LOG / LOGARITHM	:\n	return the natural log of an argument OR the log of one argument in terms of another (log A / log b). Accepts one or two arguments.");
		puts ("MOD / MODULUS	:\n	return the remainder of one argument divided by another. Accepts two arguments.");
		puts ("PI	:\n	return the value of pi. Accepts no arguments.");
		puts ("POW / POWER	:\n	return the value of one argument raised to the power of the other. Accepts two arguments.");
		puts ("PROD / PRODUCT	:\n	return the product of the arguments. Accepts one or more arguments.");
		puts ("SIN / SINE	:\n	return the sine of the argument. Accepts one argument.");
		puts ("SQRT / SQUARE_ROOT	:\n	return the square root of the argument. Accepts one argument.");
		puts ("SUM / SUMMATION	:\n	return the sum of the arguments. Accepts one or more arguments.");
		puts ("TAN / TANGENT	:\n	return the tangent of the argument. Accepts one argument.");
		
		HandleError (and, 0, &look);
		return 0;
	}
	else if (!strcmp (and.Token, "QUIT")) {	// quit calculator
		HandleError (and, 0, &look);
		return 1;
	}
	
	struct TokenStruct /*Oper*/ator;
	struct TokenStruct tmp;
	tmp.Token = malloc (sizeof (char) * 2);
	tmp.Token = "+";
	tmp.type = TokenType ('+');
	tmp.priority = OpPriority ('+');
	
	if (!and.priority) { return 0; }		// no operand; blank line

	double result = 0.0;
	double sign = 1.0;
	if (and.Token[0] == '-') {				// negative value
		sign = -1.0;
		and = NextToken (&look);
	}
	
	if (and.Token[0] == '(') { result = sign * EvalSubStatement (&status, &look, Vars); }		// substatement	
	if (status) { return 0; }

	ator = NextToken (&look);				// must be determined *after* substatement, and *before* function, assignment, or variable
	
	// function, assignment, or variable; need operator to decide
	if (ator.Token[0] == '(') {				// function
		result = sign * EvalFunction (and, &status, &look, Vars);
		if (status) {
			if (status == 5 || status == 9) { HandleError (and, status, &look); }
			return 0;
		}
		
		ator = NextToken (&look);
		result = Evaluate (result, ator, &status, &look, Vars);
	}
	else if (and.type == 1 && ator.Token[0] == '=') { result = Evaluate (0.0, tmp, &status, &look, Vars); }	// assignment; don't need to check status here since it will be checked as soon as this statement is finished
	else {	// variable, number, substatement, or invalid
		if (and.Token[0] != '(') {
			result = sign * Resolve (and, &status, Vars);
			if (status) {
				HandleError (and, status, &look);
				return 0;
			}
		}
		result = Evaluate (result, ator, &status, &look, Vars);
	}

	if (status) { return 0; }
	else if (ator.Token[0] == '=') {
		AssignValue (and.Token, result, Vars);
		printf ("%s ", and.Token);
	}
	printf ("= %f;\n", result);
	return 0;
}
예제 #8
0
double Evaluate (double acc, struct TokenStruct op, char *status, char *look, struct Variable *Vars) {
#ifdef DEBUG
	printf ("Evaluate in; acc: %f, op: %s, status: %i, look: %c;\n", acc, op.Token, *status, *look);
#endif
/*	if (*status > 0) {	// if there are errors from other routines, handle error
		return;
	}*/
	if (!op.priority) {	// no operator present; return passed in value, if valid
		if (!*status) { return acc; }
		else if (*status < 0) { *status += 8; }
		HandleError (op, *status, look);
		return;
	}
	else if (op.priority == -1) {			// invalid operator
		*status = 1;
		HandleError (op, *status, look);
		return;
	}
	else if (op.priority == 1) {
		if (op.Token[0] == ')' && *status < 0) {
			*status = 0;
			return acc;
		}
		else if (*status == -2 && op.Token[0] == ',') { return acc; }	// end of argument
		else { *status += 8; }						// ',' after substatement (-1 -> 7) or other (0 -> 8)
		HandleError (op, *status, look);
		return;
	}
	
	struct TokenStruct val = NextToken (look);
	double cur;
	char neg = 0;
	if (val.Token[0] == '-') {	// if value is negative (has - preceding it), evaluate as negative and get next token
		neg = 1;
		val = NextToken (look);
	}
	
	if (val.Token[0] == '(') { cur = EvalSubStatement (status, look, Vars);	}	// sub statement
	if (*status > 0) { return; }		// invalid sub statement
	
	struct TokenStruct nop = NextToken (look);						// next operator
	
	if (nop.Token[0] == '(') {	// Function; TokenType (*Val) > 0 && 
		cur = EvalFunction (val, status, look, Vars);
		nop = NextToken (look);					// get operator after function
	}
	else if (val.Token[0] != '(') { cur = Resolve (val, status, Vars); }		// not a function or substatement, so resolve normally

	if (*status > 0) {		// invalid function or value
		HandleError (val, *status, look);
		return;
	}
	
	if (neg) { cur *= -1.0; }	// account for negative numbers
	
	switch (op.Token[0]) {
		case '+':
			if (nop.priority <= op.priority) { return Evaluate (acc + cur, nop, status, look, Vars); }	// operator has equal or greater precedence than next operator
			else { return acc + (Evaluate (cur, nop, status, look, Vars)); }						// operator has less precedence than next operator
			
		case '-':
			if (nop.priority <= op.priority) { return Evaluate (acc - cur, nop, status, look, Vars); }
			else { return acc - (Evaluate (cur, nop, status, look, Vars)); }
		
		case '*':
			if (nop.priority <= op.priority) { return Evaluate (acc * cur, nop, status, look, Vars); }
			else { return acc * (Evaluate (cur, nop, status, look, Vars)); }
			
		case '/':
			if (nop.priority <= op.priority) { return Evaluate (acc / cur, nop, status, look, Vars); }
			else { return acc / (Evaluate (cur, nop, status, look, Vars)); }
		
		case '%':
			if (nop.priority <= op.priority) { return Evaluate (fmod (acc, cur), nop, status, look, Vars); }
			else { return fmod (acc, (Evaluate (cur, nop, status, look, Vars))); }

		case '^':
			if (nop.priority <= op.priority) { return Evaluate (pow (acc, cur), nop, status, look, Vars); }
			else { return pow (acc, (Evaluate (cur, nop, status, look, Vars))); }
	}
	
	*status = 1;
	HandleError (op, *status, look);
	return;	// invalid operator
}
예제 #9
0
int main(){

std::cout<<"* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * "<<std::endl;
std::cout<<"Ce programme permettra de réaliser des opérations floues sur une base de faits et une base de règles à l'aide d'un fuzzifier"<<std::endl;
std::cout<<"* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * "<<std::endl;
std::cout<<"                                                                                                                            "<<std::endl;


char* filename;
//std::cout<<"Entrer le nom d'un fichier texte à analyser pour créer la base de faits"<<std::endl;
//std::cin>>filename;
//std::cout<<"Génération de la base de faits à base du fichier texte spécifié ... "<<std::endl;

//on parse les fichiers texte
std::vector<Fait> Faits = Parser_faits("faits.txt");

//on parse les regeles
std::vector<Rule> Rules = Parser_rules("rules.txt");

//update de la base de faits en prenant en compte la base de rules (MAJ de l'énoncé)

Faits = updateFaits(Faits, Rules);


//fonction MAJ1 de l'énoncé: créé la liste des métarègles et update les faits avec la
// std::vector<Rule> MetaRules = updateMeta(Faits, Rules);
// on verra plus tard pour les metaregles




//check à l'écran la base de faits

printFaits(Faits);
sleep(5);


printRules(Rules);
sleep(5);



//on créé notre matrice de transition entre les valeurs :
//     AB   B   TB
// AB  1    1   1
// B   0.7  1   1
// TB  0.3  0.8 1

std::vector<std::vector<double>> TransMatrix = {{1.,1.,1.},{0.7,1.,1.},{0.3,0.8,1.}};

// Créer la liste de conclusion à évaluer

std::vector<EvalConcl> EvalConcls = EvalFunction(Faits, Rules, TransMatrix);

std::cout << "Travail de fuzzification en cours ..." << std::endl;
sleep(5);

std::cout<< "Affiche des conclusions et de leur évaluations: "<<std::endl;
std::cout<< "************************************************" << std::endl;

//Affichage des conclusions évaluées
for(std::vector<EvalConcl>::iterator ite=EvalConcls.begin();ite!=EvalConcls.end();++ite){
	std::cout<<"Conclusion :"<<std::get<0>(ite->first)<<std::endl;
	std::cout<<"Et l'évaluation pour cette conclusion est : " << ite->second << std::endl;
	std::cout<< "                                      " << std::endl;


}




//on créé nos vecteurs de valeur de fait
double listB[] = {0.001,0.005,0.005,0.01,0.1,0.3,0.4,0.6,0.8,0.9,1.0};
std::vector<double> uB (11);
std::vector<double> uTB(11);

uB[0]=0.001;
uB[1]=0.005;
uB[2]=0.005;
uB[3]=0.01;
uB[4]=0.1;
uB[5]=0.3;
uB[6]=0.4;
uB[7]=0.6;
uB[8]=0.8;
uB[9]=0.9;
uB[10]=1.0;


//it=uTB.begin(;)
for( std::vector<double>::iterator it = uB.begin() ; it != uB.end(); ++it){
	double value = *it;
	uTB.push_back(value*value);
	//std::cout<<uTB.back()<<std::endl;
}

/*
std::tuple<std::string, std::string, double> line;
std::vector<std::tuple<std::string, std::string, double>> parsed_file;
 parsed_file.emplace_back("test","test",0);
std::cout<< std::get<0>(parsed_file[0]) << std::get<1>(parsed_file[0]) << std::get<2>(parsed_file[0]) << std::endl ;
*/


return 0;
}