Proyecto

General

Perfil

Diferencias con el ex4j original » Histórico » Revisión 2

Revisión 1 (Federico Vera, 2018-07-12 22:11) → Revisión 2/4 (Federico Vera, 2018-07-12 22:30)

# Diferencias con el ex4j original 

 {{>toc}} 
 # Nota 
 Existen muchas diferencias con `exp4j` original, algunas de las cuales pueden causar problemas de compatibilidad para usuarios avanzados de `exp4j`. 

 # Diferencias Generales 
 Entre los cambios mas significativos de esta versión de `exp4j` se encuentran: un simplificador (preevaluador), manejo de variables, funciones adicionales, enums, [[Diferencias_con_el_ex4j_original#Constantes-como-funciones|*constantes [[Diferencias con el ex4j original#Constantes como funciones|*constantes como funciones*]] e impresión de tokens. 

 ## Simplificador (preevaluador) 
 El simplificador es una funcionalidad intereante ([discusión original](https://github.com/fasseg/exp4j/issues/26)) cuando las expresiones tienen operaciones conocidas en tiempo de creación, por ejemplo, consideremos la expresión Naive Simplifier  
 The simplifier is a nice feature ([Original discussion](https://github.com/fasseg/exp4j/issues/26)) when you have operations that can be resolved the use of variables, for instance consider the expression `2^x + 4 / 2` que puede convertirse en could be turned into `2^x + 2`. No parece demasiado.... o si? la realidad es que al utilizar múltiples evaluaciones, muchas constantes varios valores de Doesn't seem like much... does it? but when you use multiple formulas, lots of constants, multiple `x` (por ejemplo al graficar) esta diferencia es muy notoria ([primera prueba de performance](https://github.com/fasseg/exp4j/issues/26#issuecomment-70547026)). values (i.e. plotting) this little difference comes in handy ([First performance test](https://github.com/fasseg/exp4j/issues/26#issuecomment-70547026)). 

 Otra simplificación interesante es al utilizar expresiones del tipo The other nice trick is when using expressions like `if(exp, v_true, v_false)`, el simplificador puede quitar (en algunos casos) el bloque the simplifier could remove the entire `if` completo, por ejemplo block, for instance `if(1 > 0 & 3 < 4, a * pi(), e())` se convierte en will be converted to `a * pi()` (de hecho en (actually to `if(1, a * pi(), e())`... _Todavía estoy trabajando en esto..._ _I'm still working on it..._ 

 ### Usando el simplificador Using the Simplifier 
 Por defecto se encuentra desactivado, dado que no es realmente necesarios cuando se ejecuta una operación una sola vez (el simplificador hace toda una evaluación para funcionar). The simplifier is disabled by default, since it's really not needed when evaluating an expression only once (the simplifier needs to do one whole evaluation in order to work).  

 Para activar el simplificador simplemente es necesario pasar To activate it simply pass `true` al to the builder: 

 ~~~java 
     // por defecto by default ExpressionBuilder#build() es is #build(false) 
     Expression ex = new ExpressionBuilder("2^3 + 4 / 2").build(true); 
     double result = ex.evaluate(); 
 ~~~ 

 ### Una pequeña nota A little note 
 Un simplificador _**debería**_ simplificar solamente funciones determinísticas, por lo tanto ahora disponemos de una bandera A simplifier _**should**_ only simplify deterministic functions, so there's now a `deterministic` en el constructor de las funciones (valor por defecto `true`). Por lo tanto si utiliza funciones [no deterministas](https://es.wikipedia.org/wiki/Algoritmo_no_determinista) deberá cambiar la declaración de la función a: flag in each function creation (`true` by default). So if you have [non-deterministic](https://en.wikipedia.org/wiki/Nondeterministic_algorithm) functions in your code, you'll need to change your function declaration from this: 

 ~~~java 
     Function rand_deterministica rand_deterministic = new Function("randd", 0) { 
         @Override 
         public double apply(double... args) { 
             // Falla épica de simplificación This will be an epic simplification fail 
             return Math.random(); 
         } 
     }; 
 ~~~ 
 A esto: To this: 
 ~~~java 
     Function rand_NO_deterministica rand_NOT_deterministic = new Function("randnd", 0, false) { 
     //                                               Esta bandera                                                  This flag ^^^^^ 
         @Override 
         public double apply(double... args) { 
             return Math.random(); 
         } 
     }; 
 ~~~ 

 Este cambio puede resultar molesto para aquellos que utlicen muchas funciones no deterministas... aunque dado que el simplificador está desactivado por defecto, la mayoría de la gente no debería tener problemas. This will be the most annoying thing for users with lot's of custom non-deterministic functions... although most users should not notice it (simplifier is disabled by default) 

 ## Internal variable handling 
 This isn't really an issue in itself, it makes `exp4j` gain some performance, avoid possible errors, and improve code readability. But doesn't honor the _inmutable token_ filosophy of both `exp4j` and stack based calculators, so if you want to start hacking in this fork you should take this into account. 

 ### So... what's the change? 
 The real changes is commit:d2d96fce and in commit:7f280988 you can see an example of one the pitfalls. 

 The original `exp4j` uses one token per variable, that's to say one token each time a variable is present in an expression which creates every time a variable is set, a state where the same variable has a different values in an expression. That's really a no go for me. 

 This version of `exp4j` uses the same token for each and every time a variable is present in an expression, which means that the moment you set a variable it was changed in every occurrence. 

 ## Enums instead of final int variables 
 This should not be a problem for anybody, but it's necessary to address the change `->` commit:39dff556. 

 ## Token printing 
 Some might call this a debugging tool, others the reason of a 50% increase in the final jar size, I simply call it token printing... it allowed me create a view of the internal expression.  
 ### Why should you care?  
 Well the thing is, you probably won't, but there are some cases when using this sort of tools for research you need a way to audit the internals of the expression, not to try and guarantee result reproducibility, but to build extra trust in the expression that's being evaluated (_also... it's an awesome debbuging tool!_). 
 ### How to print the tokens? 
 The two basic ways are: 
 ~~~java 
    Expression exp = new ExpressionBuilder("2x + 1").variable("x").build(); 
    String out1 = exp.toString(); 
    // out1 -> 2.0 x * 1.0 + 
    String out2 = exp.toTokenString(); 
    // out2 -> NUMBER[2.0] VARIABLE[x] OPERATOR[*] NUMBER[1.0] OPERATOR[+] 
 ~~~ 

 ## Constantes como funciones 
 We finally got to the change that will annoy most users and it's the change that will most probably _break_ things. In the original `exp4j` the constants where declared as simply constants, in this version constants are declared as functions so for instance `d * pi` is now `d * pi()`, this isn't an extreme change, but the reasoning is: some times your variables can have the name of constants... since users are not expected to know each and every constant implemented in `exp4j` this can cause trouble. 

 ## Traducciones Translations 
 Todos los mensajes y advertencias pueden ser traducidos, y ya se tiene la primera traducción al Español All messages can now be translated, and have already been translated to Spanish. 

 ## Serialización Serialization 
 Todas las expresiones son `Serializable`s! All expressions are now `Serializable`! 

 ## Funciones adicionales Extra functions 
 Checkout the wiki pages for: 
 * [[Funciones Incluidas]] [[Built in Functions]] 
 * [[Operadores Incluidos]] [[Built in Operators]] 
 * [[Funciones y Operadores adicionales]] [[Extra Functions and Operators]]
Volver al inicio