Skip to content

Commit e94892d

Browse files
authored
Merge pull request #200 from joaquinelio/numbers
Numbers
2 parents 6be9c5c + 71e68bc commit e94892d

File tree

13 files changed

+216
-217
lines changed

13 files changed

+216
-217
lines changed
Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
11

22

33
```js run demo
4-
let a = +prompt("The first number?", "");
5-
let b = +prompt("The second number?", "");
4+
let a = +prompt("¿El primer número?", "");
5+
let b = +prompt("¿El segundo número?", "");
66

77
alert( a + b );
88
```
99

10-
Note the unary plus `+` before `prompt`. It immediately converts the value to a number.
10+
Toma nota del más unario `+` antes del `prompt`. Este convierte inmediatamente el valor a `number`.
1111

12-
Otherwise, `a` and `b` would be string their sum would be their concatenation, that is: `"1" + "2" = "12"`.
12+
De otra manera `a` and `b` serían `string`, y la suma, su concatenación: `"1" + "2" = "12"`.

1-js/05-data-types/02-number/1-sum-interface/task.md

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,10 @@ importance: 5
22

33
---
44

5-
# Sum numbers from the visitor
5+
# Suma números del visitante
66

7-
Create a script that prompts the visitor to enter two numbers and then shows their sum.
7+
Crea un script que pida al visitante que ingrese dos números y muestre su suma.
88

99
[demo]
1010

11-
P.S. There is a gotcha with types.
11+
P.D. Hay una trampa con los tipos de valores.
Lines changed: 9 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,33 +1,32 @@
1-
Internally the decimal fraction `6.35` is an endless binary. As always in such cases, it is stored with a precision loss.
1+
Internamente, la fracción decimal `6.35` resulta en binario sin fin. Como siempre en estos casos, es almacenado con pérdida de precisión.
22

3-
Let's see:
3+
Veamos:
44

55
```js run
66
alert( 6.35.toFixed(20) ); // 6.34999999999999964473
77
```
88

9-
The precision loss can cause both increase and decrease of a number. In this particular case the number becomes a tiny bit less, that's why it rounded down.
9+
La pérdida de precisión puede causar que el número incremente o decremente. En este caso particular el número se vuelve ligeramente menor, por ello es redondeado hacia abajo.
1010

11-
And what's for `1.35`?
11+
¿Y qué pasa con `1.35`?
1212

1313
```js run
1414
alert( 1.35.toFixed(20) ); // 1.35000000000000008882
1515
```
1616

17-
Here the precision loss made the number a little bit greater, so it rounded up.
17+
Aquí la pérdida de precisión hace el número algo mayor, por ello redondea hacia arriba.
1818

19-
**How can we fix the problem with `6.35` if we want it to be rounded the right way?**
19+
**¿Cómo podemos arreglar el problema con `6.35` si queremos redondearlo de manera correcta?**
2020

21-
We should bring it closer to an integer prior to rounding:
21+
Debemos llevarlo más cerca de un entero antes del redondeo:
2222

2323
```js run
2424
alert( (6.35 * 10).toFixed(20) ); // 63.50000000000000000000
2525
```
2626

27-
Note that `63.5` has no precision loss at all. That's because the decimal part `0.5` is actually `1/2`. Fractions divided by powers of `2` are exactly represented in the binary system, now we can round it:
27+
Observa que `63.5` no tiene pérdida de precisión en absoluto. Esto es porque la parte decimal `0.5` es realmente `1/2`. Fracciones divididas por potencias de `2` son representadas exactamente en el sistema binario, ahora podemos redondearlo:
2828

2929

3030
```js run
31-
alert( Math.round(6.35 * 10) / 10); // 6.35 -> 63.5 -> 64(rounded) -> 6.4
31+
alert( Math.round(6.35 * 10) / 10); // 6.35 -> 63.5 -> 64(redondeado) -> 6.4
3232
```
33-

1-js/05-data-types/02-number/2-why-rounded-down/task.md

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,21 +2,21 @@ importance: 4
22

33
---
44

5-
# Why 6.35.toFixed(1) == 6.3?
5+
# ¿Por qué 6.35.toFixed(1) == 6.3?
66

7-
According to the documentation `Math.round` and `toFixed` both round to the nearest number: `0..4` lead down while `5..9` lead up.
7+
Según la documentación `Math.round` y `toFixed` redondean al número más cercano: `0..4` hacia abajo mientras `5..9` hacia arriba.
88

9-
For instance:
9+
Por ejemplo:
1010

1111
```js run
1212
alert( 1.35.toFixed(1) ); // 1.4
1313
```
1414

15-
In the similar example below, why is `6.35` rounded to `6.3`, not `6.4`?
15+
En el ejemplo similar que sigue, ¿por qué `6.35` es redondeado a `6.3`, y no a `6.4`?
1616

1717
```js run
1818
alert( 6.35.toFixed(1) ); // 6.3
1919
```
2020

21-
How to round `6.35` the right way?
21+
¿Cómo redondear `6.35` de manera correcta?
2222

1-js/05-data-types/02-number/3-repeat-until-number/solution.md

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ function readNumber() {
44
let num;
55

66
do {
7-
num = prompt("Enter a number please?", 0);
7+
num = prompt("Ingrese un número por favor:", 0);
88
} while ( !isFinite(num) );
99

1010
if (num === null || num === '') return null;
@@ -15,9 +15,8 @@ function readNumber() {
1515
alert(`Read: ${readNumber()}`);
1616
```
1717

18-
The solution is a little bit more intricate that it could be because we need to handle `null`/empty lines.
18+
La solución es un poco más intrincada de lo que podría ser porque necesitamos manejar `null` y líneas vacías.
1919

20-
So we actually accept the input until it is a "regular number". Both `null` (cancel) and empty line also fit that condition, because in numeric form they are `0`.
21-
22-
After we stopped, we need to treat `null` and empty line specially (return `null`), because converting them to a number would return `0`.
20+
Entonces aceptamos entrada de datos hasta que sea un "número regular". También `null` (cancel) y las líneas vacías encajan en esa condición porque un su forma numérica estos son `0`.
2321

22+
Una vez detenido el ingreso, necesitamos tratar especialmente los casos `null` y línea vacía (return `null`), porque al convertirlos devolverían `0`.

1-js/05-data-types/02-number/3-repeat-until-number/task.md

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,13 @@ importance: 5
22

33
---
44

5-
# Repeat until the input is a number
5+
# Repetir hasta que lo ingresado sea un número
66

7-
Create a function `readNumber` which prompts for a number until the visitor enters a valid numeric value.
7+
Crea una función `readNumber` que pida un número hasta que el visitante ingrese un valor numérico válido.
88

9-
The resulting value must be returned as a number.
9+
El valor resultante debe ser devuelto como number.
1010

11-
The visitor can also stop the process by entering an empty line or pressing "CANCEL". In that case, the function should return `null`.
11+
El visitante puede también detener el proceso ingresando una linea vacía o presionando "CANCEL". En tal caso la función debe devolver `null`.
1212

1313
[demo]
1414

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
1-
That's because `i` would never equal `10`.
1+
Es porque `i` nunca sería igual a `10`.
22

3-
Run it to see the *real* values of `i`:
3+
Ejecuta esto para ver los valores *reales* de `i`:
44

55
```js run
66
let i = 0;
@@ -10,8 +10,8 @@ while (i < 11) {
1010
}
1111
```
1212

13-
None of them is exactly `10`.
13+
Ninguno de ellos es exactamente `10`.
1414

15-
Such things happen because of the precision losses when adding fractions like `0.2`.
15+
Tales cosas suceden por las pérdidas de precisión cuando sumamos decimales como `0.2`.
1616

17-
Conclusion: evade equality checks when working with decimal fractions.
17+
Conclusión: evita chequeos de igualdad al trabajar con números decimales.

1-js/05-data-types/02-number/4-endless-loop-error/task.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,9 @@ importance: 4
22

33
---
44

5-
# An occasional infinite loop
5+
# Un bucle infinito ocasional
66

7-
This loop is infinite. It never ends. Why?
7+
Este bucle es infinito. Nunca termina, ¿por qué?
88

99
```js
1010
let i = 0;

1-js/05-data-types/02-number/8-random-min-max/solution.md

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
1-
We need to "map" all values from the interval 0..1 into values from `min` to `max`.
1+
Necesitamos hacer un "mapeo" de todos los valores del intervalo 0..1 a valores desde `min` a `max`.
22

3-
That can be done in two stages:
3+
Esto puede hacerse en dos pasos:
44

5-
1. If we multiply a random number from 0..1 by `max-min`, then the interval of possible values increases `0..1` to `0..max-min`.
6-
2. Now if we add `min`, the possible interval becomes from `min` to `max`.
5+
1. Si multiplicamos el número aleatorio 0..1 por `max-min`, entonces el intervalo de valores posibles va de `0..1` a `0..max-min`.
6+
2. Ahora si sumamos `min`, el intervalo posible se vuelve desde `min` a `max`.
77

8-
The function:
8+
La función:
99

1010
```js run
1111
function random(min, max) {

1-js/05-data-types/02-number/8-random-min-max/task.md

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,13 @@ importance: 2
22

33
---
44

5-
# A random number from min to max
5+
# Un número aleatorio entre min y max
66

7-
The built-in function `Math.random()` creates a random value from `0` to `1` (not including `1`).
7+
La función incorporada `Math.random()` crea un valor aleatorio entre `0` y `1` (no incluyendo `1`).
88

9-
Write the function `random(min, max)` to generate a random floating-point number from `min` to `max` (not including `max`).
9+
Escribe una función `random(min, max)` para generar un número de punto flotante entre `min` y `max` (no incluyendo `max`).
1010

11-
Examples of its work:
11+
Ejemplos de su funcionamiento:
1212

1313
```js
1414
alert( random(1, 5) ); // 1.2345623452
Lines changed: 17 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
1-
# The simple but wrong solution
1+
# La solución simple pero equivocada
22

3-
The simplest, but wrong solution would be to generate a value from `min` to `max` and round it:
3+
La solución más simple, pero equivocada, sería generar un valor entre `min` y `max` y redondearlo:
44

55
```js run
66
function randomInteger(min, max) {
@@ -11,23 +11,23 @@ function randomInteger(min, max) {
1111
alert( randomInteger(1, 3) );
1212
```
1313

14-
The function works, but it is incorrect. The probability to get edge values `min` and `max` is two times less than any other.
14+
La función funciona, pero es incorrecta. La probabilidad de obtener los valores extremos `min` y `max` es la mitad de la de los demás.
1515

16-
If you run the example above many times, you would easily see that `2` appears the most often.
16+
Si ejecutas el ejemplo que sigue muchas veces, fácilmente verás que `2` aparece más a menudo.
1717

18-
That happens because `Math.round()` gets random numbers from the interval `1..3` and rounds them as follows:
18+
Esto ocurre porque `Math.round()` obtiene los números del intervalo `1..3` y los redondea como sigue:
1919

2020
```js no-beautify
21-
values from 1 ... to 1.4999999999 become 1
22-
values from 1.5 ... to 2.4999999999 become 2
23-
values from 2.5 ... to 2.9999999999 become 3
21+
valores desde 1 ... hasta 1.4999999999 se vuelven 1
22+
valores desde 1.5 ... hasta 2.4999999999 se vuelven 2
23+
valores desde 2.5 ... hasta 2.9999999999 se vuelven 3
2424
```
2525

26-
Now we can clearly see that `1` gets twice less values than `2`. And the same with `3`.
26+
Ahora podemos ver claramente que `1` obtiene la mitad de valores que `2`. Y lo mismo con `3`.
2727

28-
# The correct solution
28+
# La solución correcta
2929

30-
There are many correct solutions to the task. One of them is to adjust interval borders. To ensure the same intervals, we can generate values from `0.5 to 3.5`, thus adding the required probabilities to the edges:
30+
Hay muchas soluciones correctas para la tarea. una es ajustar los bordes del intervalo. Para asegurarse los mismos intervalos, podemos generar valores entre `0.5 a 3.5`, así sumando las probabilidades requeridas a los extremos:
3131

3232
```js run
3333
*!*
@@ -41,7 +41,7 @@ function randomInteger(min, max) {
4141
alert( randomInteger(1, 3) );
4242
```
4343

44-
An alternative way could be to use `Math.floor` for a random number from `min` to `max+1`:
44+
Una alternativa es el uso de `Math.floor` para un número aleatorio entre `min` y `max+1`:
4545

4646
```js run
4747
*!*
@@ -55,12 +55,12 @@ function randomInteger(min, max) {
5555
alert( randomInteger(1, 3) );
5656
```
5757

58-
Now all intervals are mapped this way:
58+
Ahora todos los intervalos son mapeados de esta forma:
5959

6060
```js no-beautify
61-
values from 1 ... to 1.9999999999 become 1
62-
values from 2 ... to 2.9999999999 become 2
63-
values from 3 ... to 3.9999999999 become 3
61+
valores desde 1 ... hasta 1.9999999999 se vuelven 1
62+
valores desde 2 ... hasta 2.9999999999 se vuelven 2
63+
valores desde 3 ... hasta 3.9999999999 se vuelven 3
6464
```
6565

66-
All intervals have the same length, making the final distribution uniform.
66+
Todos los intervalos tienen el mismo largo, haciendo la distribución final uniforme.

1-js/05-data-types/02-number/9-random-int-min-max/task.md

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,19 +2,19 @@ importance: 2
22

33
---
44

5-
# A random integer from min to max
5+
# Un entero aleatorio entre min y max
66

7-
Create a function `randomInteger(min, max)` that generates a random *integer* number from `min` to `max` including both `min` and `max` as possible values.
7+
Crea una función `randomInteger(min, max)` que genere un número *entero* aleatorio entre `min` y `max` incluyendo ambos, `min` y `max`, como valores posibles.
88

9-
Any number from the interval `min..max` must appear with the same probability.
9+
Todo número del intervalo `min..max` debe aparecer con la misma probabilidad.
1010

1111

12-
Examples of its work:
12+
Ejemplos de funcionamiento:
1313

1414
```js
1515
alert( randomInteger(1, 5) ); // 1
1616
alert( randomInteger(1, 5) ); // 3
1717
alert( randomInteger(1, 5) ); // 5
1818
```
1919

20-
You can use the solution of the [previous task](info:task/random-min-max) as the base.
20+
Puedes usar la solución de la [tarea previa](info:task/random-min-max) como base.

0 commit comments

Comments
 (0)