···11---
22-title: Comparison
33-description: Explanation of the various pitfalls in comparing floating-point numbers.
22+title: Comparación
33+description: Explicación de los diversos problemas al comparar números de punto flotante
44---
5566-Due to rounding errors, most [floating-point](/formats/fp/) numbers end up being slightly imprecise. As long as this
77-imprecision stays small, it can usually be ignored. However, it also means that numbers expected
88-to be equal (e.g. when calculating the same result through different correct methods) often differ
99-slightly, and a simple equality test fails. For example:
66+Debido a los errores de redondeo, la mayoría de los números de [punto flotante](/formats/fp/)
77+terminan siendo ligeramente imprecisos. Mientras esta imprecisión se mantenga pequeña,
88+normalmente se puede ignorar. Sin embargo, esto significa también que números que se
99+espera que sean iguales (por ejemplo al calcular el mismo resultado utilizando distintos
1010+métodos correctos) a veces difieren levemente, y una simple prueba de igualdad falla.
1111+Por ejemplo:
10121113 float a = 0.15 + 0.15
1214 float b = 0.1 + 0.2
1313- if(a == b) // can be false!
1414- if(a >= b) // can also be false!
1515+ if(a == b) // ¡Puede ser falso!
1616+ if(a >= b) // ¡También puede ser falso!
15171616-Don't use absolute error margins
1717---------------------------------
1818-The solution is to check not whether the numbers are exactly the same, but whether their difference is
1919-very small. The error margin that the difference is compared to is often called *epsilon*.
2020-The most simple form:
1818+No usar márgenes de error absolutos
1919+-----------------------------------
21202222- if( Math.abs(a-b) < 0.00001) // wrong - don't do this
2121+La solución es comprobar no si los números son exactamente iguales, sino si su
2222+diferencia es muy pequeña. El margen de error frente al que se compara esta diferencia
2323+normalmente se llama *epsilon*. En su forma más simple:
23242424-This is a bad way to do it because a fixed epsilon chosen because it "looks small" could actually be way too
2525-large when the numbers being compared are very small as well. The comparison would return "true" for numbers that are quite different. And when the numbers are very large, the epsilon
2626-could end up being smaller than the smallest rounding error, so that the comparison always returns "false".
2727-Therefore, it is necessary to see whether the *relative error* is smaller than epsilon:
2525+ if(Math.abs(a-b) < 0.00001) // Mal - no hacer esto
28262929- if( Math.abs((a-b)/b) < 0.00001 ) // still not right!
2727+Esto es una mala forma de hacerlo porque un epsilon fijo elegido porque «parece
2828+pequeño» podría perfectamente ser demasiado grande cuando los números que se
2929+comparan son también muy pequeños. La comparación devolvería «verdadero» para
3030+números muy diferentes. Y cuando los números son muy grandes, el epsilon
3131+puede acabar siendo más pequeño que el mínimo error de redondeo, por lo que
3232+la comparación siempre devolvería «falso». Por tanto, es necesario ver si
3333+el *error relativo* es menor epsilon:
30343131-Look out for edge cases
3535+ if(Math.abs((a-b)/b) < 0.00001) // ¡Todavía no es correcto!
3636+3737+Vigila los casos límite
3238-----------------------
3333-There are some important special cases where this will fail:
3939+4040+Hay algunos casos especiales importantes para los que esto falla:
34413535-* When both `a` and `b` are zero. `0.0/0.0` is "not a number", which causes an exception on some platforms, or returns false for all comparisons.
3636-* When only `b` is zero, the division yields "infinity", which may also cause an exception, or is greater than epsilon even when `a` is smaller.
3737-* It returns `false` when both `a` and `b` are very small but on opposite sides of zero, even when they're the smallest possible non-zero numbers.
4242+* Cuando tanto `a` como `b` son cero. `0.0/0.0` es NaN, lo que provoca una excepción en algunas plataformas o devuelve falso para todas las comparaciones.
4343+* Cuando solo `b` es cero, la división devuelve infinito, lo que también puede causar una excepción, o es mayor que epsilon incluso cuando `a` es más pequeño.
4444+* Devuelve «falso» cuando tanto `a` como `b` son muy pequeños pero a ambos lados del cero, incluso cuando son los números no nulos más pequeños.
38453939-Also, the result is not commutative (`nearlyEquals(a,b)` is not always the same as `nearlyEquals(b,a)`). To fix these problems, the code has to get a lot more complex, so we really need to put it into a function of its own:
4646+Además, el resultado no es conmutativo (`nearlyEquals(a,b)` no es siempre lo mismo que
4747+`nearlyEquals(b,a)`). Para solucionar estos problemas, el código tiene que ser mucho más
4848+complejo, así que necesitamos meterlo en una función:
40494150 public static boolean nearlyEqual(float a, float b, float epsilon)
4251 {
···4453 final float absB = Math.abs(b);
4554 final float diff = Math.abs(a - b);
46554747- if (a == b) { // shortcut, handles infinities
5656+ if (a == b) { // Atajo, maneja los infinitos
4857 return true;
4949- } else if (a * b == 0) { // a or b or both are zero
5050- // relative error is not meaningful here
5858+ } else if (a * b == 0) { // a o b o ambos son cero
5959+ // El error relativo no es importante aquí
5160 return diff < (epsilon * epsilon);
5252- } else { // use relative error
6161+ } else { // Usar el error relativo
5362 return diff / (absA + absB) < epsilon;
5463 }
5564 }
56655757-This method [passes tests](../NearlyEqualsTest.java) for many important special cases, but as you can see, it
5858-uses some quite non-obvious logic. In particular, it has to use a completely different definition of error margin
5959-when `a` or `b` is zero, because the classical definition of relative error becomes meaningless in those cases.
6666+Este método [pasa las pruebas](../NearlyEqualsTest.java) para muchos casos especiales
6767+importantes, pero como puedes ver, utiliza cierta lógica no trivial. En particular,
6868+tiene que utilizar una definición totalmente distinta del margen de error cuando
6969+`a` o `b` son cero, porque la definición clásica del error relativo es inútil en
7070+esos casos.
7171+7272+Hay algunos casos en los que el método de arriba todavía produce resultados inesperados
7373+(concretamente, es mucho más estricto cuando un valor es casi cero que cuando es
7474+exactamente cero), y algunas de esas pruebas para las que fue desarrollado probablemente
7575+especifica un comportamiento que no es apropiado para algunas aplicaciones. ¡Antes de
7676+usarlo, asegúrate de que es adecuado para tu aplicación!
60776161-There are some cases where the method above still produces unexpected results (in particular, it's much stricter when one value is nearly zero than when it is exactly zero), and some of the tests
6262-it was developed to pass probably specify behaviour that is not appropriate for some applications. Before using it, make sure it's appropriate for your application!
7878+Comparando valores de punto flotante como enteros
7979+-------------------------------------------------
63806464-Comparing floating-point values as integers
6565--------------------------------------------
6666-There is an alternative to heaping conceptual complexity onto such an apparently simple task: instead of comparing `a` and `b` as [real numbers](http://en.wikipedia.org/wiki/Real_numbers), we can think about them as discrete steps and define the error margin as the maximum number of possible floating-point values between the two values.
8181+Hay una alternativa a aplicar toda esta complejidad conceptual a una tarea aparentemente
8282+tan sencilla: en lugar de comparar `a` y `b` como [números
8383+reales](http://es.wikipedia.org/wiki/N%C3%BAmero_real), podemos concebirlos como pasos
8484+discretos y definir el margen de error como el número máximo de valores de punto flotante
8585+posibles entre esos dos números.
67866868-This is conceptually very clear and easy and has the advantage of implicitly scaling the relative error margin with the magnitude of the values. Technically, it's a bit more complex, but not as much as you might think, because IEEE 754 floats are designed to maintain their order when their bit patterns are interpreted as integers.
8787+Esto es conceptualmente muy evidente y fácil y tiene la ventaja de que escala
8888+implícitamente el margen de error relativo con la magnitud de los valores.
8989+Técnicamente es un poco más complejo, pero no mucho más de lo que puedas pensar,
9090+porque los números del IEEE 754 están diseñados para mantener su orden cuando
9191+sus secuencias de bits se interpretan como enteros.
69927070-However, this method does require the programming language to support conversion between floating-point values and integer bit patterns. Read the [Comparing floating-point numbers](/references/) paper for more details.9393+Sin embargo, este método requiere que el lenguaje de programación soporte conversión
9494+entre valores de punto flotante y secuencias de bits enteras. Lee el artículo en
9595+inglés [Comparing floating-point numbers](/references/) para más detalles.
+18-22
content/errors/propagation.html
···11---
22-title: Error Propagation
33-description: Explanations about propagation of errors in floating-point math.
22+title: Propagación del error
33+description: Explicaciones sobre la propagación de errores en aritmética de punto flotante
44---
5566-While the errors in single [floating-point numbers](/formats/fp/) are very small, even simple calculations on them
77-can contain pitfalls that increase the error in the result way beyond just having the individual
88-errors "add up".
66+Aunque los errores en [números de punto flotante](/formats/fp/) aislados son muy pequeños,
77+operaciones simples con ellos pueden tener problemas e incrementar el error del resultado
88+más de lo que se esperaría «sumando» los errores individuales.
991010-In general:
1010+En general:
11111212-* Multiplication and division are "safe" operations
1313-* Addition and subtraction are dangerous, because when numbers of different magnitudes are involved,
1414- digits of the smaller-magnitude number are lost.
1515-* This loss of digits can be inevitable and benign (when the lost digits also insignificant for
1616- the final result) or catastrophic (when the loss is magnified and distorts the result strongly).
1717-* The more calculations are done (especially when they form an iterative algorithm) the more important
1818- it is to consider this kind of problem.
1919-* A method of calculation can be *stable* (meaning that it tends to reduce rounding errors)
2020- or *unstable* (meaning that rounding errors are magnified). Very often, there are both stable
2121- and unstable solutions for a problem.
1212+* La multiplicación y la división son operaciones «seguras».
1313+* La suma y la resta son peligrosas, porque cuando hay involucrados números de diferentes órdenes de magnitud, los dígitos del más pequeño se pierden.
1414+* Esta pérdida de dígitos puede ser inevitable y benigna (cuando los dígitos perdidos son también insignificantes para el resultado final) o catastrófica (cuando la pérdida se amplifica y distorsiona el resultado fuertemente).
1515+* Cuantas más operaciones se hagan (especialmente cuando forman parte de un algoritmo iterativo) más importante es considerar este problema.
1616+* Un método de cálculo puede ser *estable* (tiende a reducir los errores de redondeo) o *inestable* (los errores de redondeo se amplifican). A menudo, hay soluciones estables e inestables a un problema.
22172323-There is an entire sub-field of mathematics (in [numerical analysis](http://en.wikipedia.org/wiki/Numerical_analysis)) devoted to studying the numerical stability
2424-of algorithms. For doing complex calculations involving floating-point numbers, it is absolutely
2525-necessary to have some understanding of this discipline.
1818+Hay un área entera de las matemáticas (el [análisis
1919+numérico](http://es.wikipedia.org/wiki/An%C3%A1lisis_num%C3%A9rico)) dedicada a estudiar la
2020+estabilidad numérica de los algoritmos. Para hacer cálculos complejos utilizando números de punto
2121+flotante, es absolutamente necesario tener ciertos conocimientos en esta materia.
26222727-The article [What Every Computer Scientist Should Know About Floating-Point Arithmetic](/references/) gives a detailed introduction,
2828-and served as an inspiration for creating this website, mainly due to being a bit too detailed and
2929-intimidating to programmers without a scientific background.2323+Este artículo en inglés [What Every Computer Scientist Should Know About Floating-Point Arithmetic](/references/)
2424+da una introducción detallada, y sirvió de inspiración para esta web, principalmente por el hecho
2525+de que era demasiado minucioso y un poco intimidante para programadores sin una formación científica.