From a55b575e8089ee6cab7c5c262a7e6db55d0e34d6 Mon Sep 17 00:00:00 2001 From: Florian Merz Date: Thu, 11 Feb 2021 14:46:50 +0100 Subject: unslug es: move --- .../reference/global_objects/math/abs/index.html | 149 ++++++++++++++ .../reference/global_objects/math/acos/index.html | 99 ++++++++++ .../reference/global_objects/math/acosh/index.html | 94 +++++++++ .../reference/global_objects/math/asin/index.html | 144 ++++++++++++++ .../reference/global_objects/math/asinh/index.html | 90 +++++++++ .../reference/global_objects/math/atan/index.html | 107 ++++++++++ .../reference/global_objects/math/atan2/index.html | 141 +++++++++++++ .../reference/global_objects/math/atanh/index.html | 87 ++++++++ .../reference/global_objects/math/cbrt/index.html | 96 +++++++++ .../reference/global_objects/math/ceil/index.html | 166 ++++++++++++++++ .../reference/global_objects/math/cos/index.html | 74 +++++++ .../reference/global_objects/math/e/index.html | 83 ++++++++ .../reference/global_objects/math/exp/index.html | 136 +++++++++++++ .../reference/global_objects/math/expm1/index.html | 89 +++++++++ .../reference/global_objects/math/floor/index.html | 124 ++++++++++++ .../global_objects/math/fround/index.html | 199 +++++++++++++++++++ .../reference/global_objects/math/hypot/index.html | 124 ++++++++++++ .../reference/global_objects/math/index.html | 196 ++++++++++++++++++ .../reference/global_objects/math/ln10/index.html | 84 ++++++++ .../reference/global_objects/math/ln2/index.html | 83 ++++++++ .../reference/global_objects/math/log/index.html | 112 +++++++++++ .../reference/global_objects/math/log10/index.html | 137 +++++++++++++ .../global_objects/math/log10e/index.html | 130 ++++++++++++ .../reference/global_objects/math/log2/index.html | 96 +++++++++ .../reference/global_objects/math/log2e/index.html | 27 +++ .../reference/global_objects/math/max/index.html | 145 ++++++++++++++ .../reference/global_objects/math/min/index.html | 150 ++++++++++++++ .../reference/global_objects/math/pi/index.html | 126 ++++++++++++ .../reference/global_objects/math/pow/index.html | 140 +++++++++++++ .../global_objects/math/random/index.html | 132 +++++++++++++ .../reference/global_objects/math/round/index.html | 218 +++++++++++++++++++++ .../reference/global_objects/math/sign/index.html | 151 ++++++++++++++ .../reference/global_objects/math/sin/index.html | 126 ++++++++++++ .../reference/global_objects/math/sqrt/index.html | 134 +++++++++++++ .../global_objects/math/sqrt1_2/index.html | 123 ++++++++++++ .../reference/global_objects/math/sqrt2/index.html | 124 ++++++++++++ .../reference/global_objects/math/tan/index.html | 82 ++++++++ .../reference/global_objects/math/tanh/index.html | 95 +++++++++ .../reference/global_objects/math/trunc/index.html | 144 ++++++++++++++ 39 files changed, 4757 insertions(+) create mode 100644 files/es/web/javascript/reference/global_objects/math/abs/index.html create mode 100644 files/es/web/javascript/reference/global_objects/math/acos/index.html create mode 100644 files/es/web/javascript/reference/global_objects/math/acosh/index.html create mode 100644 files/es/web/javascript/reference/global_objects/math/asin/index.html create mode 100644 files/es/web/javascript/reference/global_objects/math/asinh/index.html create mode 100644 files/es/web/javascript/reference/global_objects/math/atan/index.html create mode 100644 files/es/web/javascript/reference/global_objects/math/atan2/index.html create mode 100644 files/es/web/javascript/reference/global_objects/math/atanh/index.html create mode 100644 files/es/web/javascript/reference/global_objects/math/cbrt/index.html create mode 100644 files/es/web/javascript/reference/global_objects/math/ceil/index.html create mode 100644 files/es/web/javascript/reference/global_objects/math/cos/index.html create mode 100644 files/es/web/javascript/reference/global_objects/math/e/index.html create mode 100644 files/es/web/javascript/reference/global_objects/math/exp/index.html create mode 100644 files/es/web/javascript/reference/global_objects/math/expm1/index.html create mode 100644 files/es/web/javascript/reference/global_objects/math/floor/index.html create mode 100644 files/es/web/javascript/reference/global_objects/math/fround/index.html create mode 100644 files/es/web/javascript/reference/global_objects/math/hypot/index.html create mode 100644 files/es/web/javascript/reference/global_objects/math/index.html create mode 100644 files/es/web/javascript/reference/global_objects/math/ln10/index.html create mode 100644 files/es/web/javascript/reference/global_objects/math/ln2/index.html create mode 100644 files/es/web/javascript/reference/global_objects/math/log/index.html create mode 100644 files/es/web/javascript/reference/global_objects/math/log10/index.html create mode 100644 files/es/web/javascript/reference/global_objects/math/log10e/index.html create mode 100644 files/es/web/javascript/reference/global_objects/math/log2/index.html create mode 100644 files/es/web/javascript/reference/global_objects/math/log2e/index.html create mode 100644 files/es/web/javascript/reference/global_objects/math/max/index.html create mode 100644 files/es/web/javascript/reference/global_objects/math/min/index.html create mode 100644 files/es/web/javascript/reference/global_objects/math/pi/index.html create mode 100644 files/es/web/javascript/reference/global_objects/math/pow/index.html create mode 100644 files/es/web/javascript/reference/global_objects/math/random/index.html create mode 100644 files/es/web/javascript/reference/global_objects/math/round/index.html create mode 100644 files/es/web/javascript/reference/global_objects/math/sign/index.html create mode 100644 files/es/web/javascript/reference/global_objects/math/sin/index.html create mode 100644 files/es/web/javascript/reference/global_objects/math/sqrt/index.html create mode 100644 files/es/web/javascript/reference/global_objects/math/sqrt1_2/index.html create mode 100644 files/es/web/javascript/reference/global_objects/math/sqrt2/index.html create mode 100644 files/es/web/javascript/reference/global_objects/math/tan/index.html create mode 100644 files/es/web/javascript/reference/global_objects/math/tanh/index.html create mode 100644 files/es/web/javascript/reference/global_objects/math/trunc/index.html (limited to 'files/es/web/javascript/reference/global_objects/math') diff --git a/files/es/web/javascript/reference/global_objects/math/abs/index.html b/files/es/web/javascript/reference/global_objects/math/abs/index.html new file mode 100644 index 0000000000..eb286dcc59 --- /dev/null +++ b/files/es/web/javascript/reference/global_objects/math/abs/index.html @@ -0,0 +1,149 @@ +--- +title: Math.abs() +slug: Web/JavaScript/Referencia/Objetos_globales/Math/abs +tags: + - JavaScript + - Math + - Referencia + - metodo +translation_of: Web/JavaScript/Reference/Global_Objects/Math/abs +--- +
{{JSRef}}
+ +

La función Math.abs() retorna el valor absoluto de un número, que es 

+ +

Math.abs(x)=|x|={xifx>00ifx=0-xifx<0{\mathtt{\operatorname{Math.abs}(x)}} = {|x|} = \begin{cases} x & \text{if} \quad x \geq 0 \\ -x & \text{if} \quad x < 0 \end{cases}

+ +

Sintaxis

+ +
Math.abs(x)
+ +

Parámetros

+ +
+
x
+
Un número.
+
+

Valor de retorno

+ +

El valor absoluto del número dado.

+ +

+
+
+ +

Descripción

+ +

Como abs() es un método estático de Math, deberías siempre usar Math.abs(), en lugar de un método de un objeto Math que crees (Math no es un constructor).

+ +

Ejemplos

+ +

Comportamiento de Math.abs()

+ +

Pasando un string no-numérico o una variable {{jsxref("undefined")}}/empty retorna {{jsxref("NaN")}}. Pasando {{jsxref("null")}} retorna 0.

+ +
Math.abs('-1');     // 1
+Math.abs(-2);       // 2
+Math.abs(null);     // 0
+Math.abs('');       // 0
+Math.abs([]);       // 0
+Math.abs([2]);      // 2
+Math.abs([1,2]);    // NaN
+Math.abs({});       // NaN
+Math.abs('string'); // NaN
+Math.abs();         // NaN
+
+ +

Especificaciones

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaciónEstadoComentario
{{SpecName('ES1')}}{{Spec2('ES1')}}Definición inicial. Implementado en JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.8.2.1', 'Math.abs')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-math.abs', 'Math.abs')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-math.abs', 'Math.abs')}}{{Spec2('ESDraft')}}
+ +

Compatibilidad en navegadores

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari
Soporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Soporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Ver también

+ + diff --git a/files/es/web/javascript/reference/global_objects/math/acos/index.html b/files/es/web/javascript/reference/global_objects/math/acos/index.html new file mode 100644 index 0000000000..3280a9b17f --- /dev/null +++ b/files/es/web/javascript/reference/global_objects/math/acos/index.html @@ -0,0 +1,99 @@ +--- +title: Math.acos() +slug: Web/JavaScript/Referencia/Objetos_globales/Math/acos +tags: + - JavaScript + - Math + - Métodos + - Referências +translation_of: Web/JavaScript/Reference/Global_Objects/Math/acos +--- +
{{JSRef}}
+ +

La función Math.acos() devuelve el arco coseno (en radianes) de un número que es

+ +

x[-1;1],Math.acos(x)=arccos(x)= the unique y[0;π]such thatcos(y)=x\forall x \in [{-1};1],\;\mathtt{\operatorname{Math.acos}(x)} = \arccos(x) = \text{ the unique } \; y \in [0; \pi] \, \text{such that} \; \cos(y) = x

+ +

Sintaxis

+ +
Math.acos(x)
+ +

Parámetros

+ +
+
x
+
Un número.
+
+ +

Valor devuelto

+ +

El arco coseno (en radianes) de un número dado si se encuentra entre -1 y 1; de otro modo, {{jsxref("NaN")}}.

+ +

Descripción

+ +

El método Math.acos() devuelve un valor numérico entre 0 y π radianes para x entre -1 y 1. Si el valor de x está fuera de este rango, devuelve {{jsxref("NaN")}}.

+ +

Debido a que acos() es un método estático de Math, siempre debe usarse como Math.acos(), en vez de como un método de un objeto Math creado (Math no es un constructor).

+ +

Ejemplos

+ +

Usando Math.acos()

+ +
Math.acos(-2);  // NaN
+Math.acos(-1);  // 3.141592653589793
+Math.acos(0);   // 1.5707963267948966
+Math.acos(0.5); // 1.0471975511965979
+Math.acos(1);   // 0
+Math.acos(2);   // NaN
+
+ +

Para valores menores que  -1 o mayores que 1, Math.acos() devuelve {{jsxref("NaN")}}.

+ +

Especificaciones

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaciónEstadoComentarios
{{SpecName('ES1')}}{{Spec2('ES1')}}Definición inicial. Implementado en JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.8.2.2', 'Math.acos')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math.acos', 'Math.acos')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-math.acos', 'Math.acos')}}{{Spec2('ESDraft')}} 
+ +

Compatibilidad con navegador

+ + + +

{{Compat("javascript.builtins.Math.acos")}}

+ +

Ver también

+ + diff --git a/files/es/web/javascript/reference/global_objects/math/acosh/index.html b/files/es/web/javascript/reference/global_objects/math/acosh/index.html new file mode 100644 index 0000000000..8819e3c69a --- /dev/null +++ b/files/es/web/javascript/reference/global_objects/math/acosh/index.html @@ -0,0 +1,94 @@ +--- +title: Math.acosh() +slug: Web/JavaScript/Referencia/Objetos_globales/Math/acosh +tags: + - JavaScript + - Math + - Referencia + - metodo +translation_of: Web/JavaScript/Reference/Global_Objects/Math/acosh +--- +
{{JSRef}}
+ +

La función Math.acosh() retorna el arco coseno hiperbólico de un número que es: 

+ +

Para todo x mayor ó igual a 1,se cumple que : la funcion Math.acosh(x) = arcosh(x) = al único y mayor ó igual a 0 ; tal que; cosh(y) = x

+ +

Sintaxis

+ +
Math.acosh(x)
+ +

Parámetros

+ +
+
x
+
Un número.
+
+ +

Valor retornado

+ +

El arco coseno hiperbólico del número dado. Si el número es menor que 1, {{jsxref("NaN")}}.

+ +

Descripción

+ +

Como acosh() es un método estático de Math, siempre debe ser usado como Math.acosh(), en vez de como un método de un objeto Math creado (Math no es constructor).

+ +

Ejemplos

+ +

Utilizando Math.acosh()

+ +
Math.acosh(-1);  // NaN
+Math.acosh(0);   // NaN
+Math.acosh(0.5); // NaN
+Math.acosh(1);   // 0
+Math.acosh(2);   // 1.3169578969248166
+
+ +

Para valores menores que 1 Math.acosh() retorna {{jsxref("NaN")}}.

+ +

Polyfill

+ +

Para todo x1x mayor ó igual a 1, se tiene que el arcosh(x) = ln(x + la raiz cuadrada de(x cuadrado - 1))  y esto puede ser emulado con la siguiente funcion:

+ +
Math.acosh = Math.acosh || function(x) {
+  return Math.log(x + Math.sqrt(x * x - 1));
+};
+
+ +

Especificaciones

+ + + + + + + + + + + + + + + + + + + +
EspecificaciónStatusComentario
{{SpecName('ES6', '#sec-math.acosh', 'Math.acosh')}}{{Spec2('ES6')}}Definición inicial.
{{ SpecName('ESDraft', '#sec-math.acosh', 'Math.acosh')}}{{Spec2('ESDraft')}} 
+ +

Compatibilidad de navegador

+ + + +

{{Compat("javascript.builtins.Math.acosh")}}

+ +

Ver también

+ + diff --git a/files/es/web/javascript/reference/global_objects/math/asin/index.html b/files/es/web/javascript/reference/global_objects/math/asin/index.html new file mode 100644 index 0000000000..1a6c78d6a5 --- /dev/null +++ b/files/es/web/javascript/reference/global_objects/math/asin/index.html @@ -0,0 +1,144 @@ +--- +title: Math.asin() +slug: Web/JavaScript/Referencia/Objetos_globales/Math/asin +translation_of: Web/JavaScript/Reference/Global_Objects/Math/asin +--- +
{{JSRef}}
+ +

La Funcion Math.asin() retorna El arco seno (en radianes) de un número, eso es.

+ +

x[-1;1],Math.asin(x)=arcsin(x)= the unique y[-π2;π2]such thatsin(y)=x\forall x \in [{-1};1],\;\mathtt{\operatorname{Math.asin}(x)} = \arcsin(x) = \text{ the unique } \; y \in \left[-\frac{\pi}{2}; \frac{\pi}{2}\right] \, \text{such that} \; \sin(y) = x

+ +

Syntax

+ +
Math.asin(x)
+ +

Parametros

+ +
+
x
+
Un Numero.
+
+ +

Return value

+ +

The arcsine (in radians) of the given number if it's between -1 and 1; otherwise, {{jsxref("NaN")}}.

+ +

Descripcion

+ +

The Math.asin() method returns a numeric value between -π2-\frac{\pi}{2} and π2\frac{\pi}{2} radians for x between -1 and 1. If the value of x is outside this range, it returns {{jsxref("NaN")}}.

+ +

Because asin() is a static method of Math, you always use it as Math.asin(), rather than as a method of a Math object you created (Math is not a constructor).

+ +

Ejemplos

+ +

Usando Math.asin()

+ +
Math.asin(-2);  // NaN
+Math.asin(-1);  // -1.5707963267948966 (-pi/2)
+Math.asin(0);   // 0
+Math.asin(0.5); // 0.5235987755982989
+Math.asin(1);   // 1.5707963267948966 (pi/2)
+Math.asin(2);   // NaN
+
+ +

For values less than -1 or greater than 1, Math.asin() returns {{jsxref("NaN")}}.

+ +

Espesificaciones

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EspesificacionEstadoComentario
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.8.2.3', 'Math.asin')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math.asin', 'Math.asin')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-math.asin', 'Math.asin')}}{{Spec2('ESDraft')}} 
+ +

Compatibilidad con Navegadores

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Ver Mas

+ + diff --git a/files/es/web/javascript/reference/global_objects/math/asinh/index.html b/files/es/web/javascript/reference/global_objects/math/asinh/index.html new file mode 100644 index 0000000000..9a3204a6a8 --- /dev/null +++ b/files/es/web/javascript/reference/global_objects/math/asinh/index.html @@ -0,0 +1,90 @@ +--- +title: Math.asinh() +slug: Web/JavaScript/Referencia/Objetos_globales/Math/asinh +translation_of: Web/JavaScript/Reference/Global_Objects/Math/asinh +--- +
{{JSRef}}
+ +

La función Math.asinh() retorna el arcoseno hyperbólico de un número, es decir

+ +

Math.asinh(x)=arsinh(x)= the unique ysuch thatsinh(y)=x\mathtt{\operatorname{Math.asinh}(x)} = \operatorname{arsinh}(x) = \text{ the unique } \; y \; \text{such that} \; \sinh(y) = x

+ +

Sintáxis

+ +
Math.asinh(x)
+ +

Parámetros

+ +
+
x
+
Un número.
+
+ +

Valor de retorno

+ +

El arcoseno hyperbólico del número dado.

+ +

Descripción

+ +

Debido a que asinh() es un método estático de  Math, siempre hay que usarlo como Math.asinh(), en lugar de como un método del objeto Math que se hayamos creado (Math no es un constructor).

+ +

Ejemplos

+ +

Usos de Math.asinh()

+ +
Math.asinh(1);  // 0.881373587019543
+Math.asinh(0);  // 0
+
+ +

Polyfill

+ +

As a quick and dirty hack the expression arsinh(x)=ln(x+x2+1)\operatorname {arsinh} (x) = \ln \left(x + \sqrt{x^{2} + 1} \right) may be used directly for a coarse emulation by the following function:

+ +
Math.asinh = Math.asinh || function(x) {
+  if (x === -Infinity) {
+    return x;
+  } else {
+    return Math.log(x + Math.sqrt(x * x + 1));
+  }
+};
+
+ +

Been formally correct it suffers from a number of issues related to floating point computations. Accurate result requires special handling of positive/negative, small/large arguments as it done e.g. in glibc or GNU Scientific Library.

+ +

Especificaciones

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES6', '#sec-math.asinh', 'Math.asinh')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-math.asinh', 'Math.asinh')}}{{Spec2('ESDraft')}} 
+ +

Compatibilidades de buscadores

+ + + +

{{Compat("javascript.builtins.Math.asinh")}}

+ +

See also

+ + diff --git a/files/es/web/javascript/reference/global_objects/math/atan/index.html b/files/es/web/javascript/reference/global_objects/math/atan/index.html new file mode 100644 index 0000000000..abb0453e6c --- /dev/null +++ b/files/es/web/javascript/reference/global_objects/math/atan/index.html @@ -0,0 +1,107 @@ +--- +title: Math.atan() +slug: Web/JavaScript/Referencia/Objetos_globales/Math/atan +tags: + - JavaScript + - Matemática + - Math + - Method + - Trigonometría +translation_of: Web/JavaScript/Reference/Global_Objects/Math/atan +--- +
{{JSRef}}
+ +

La función Math.atan() retorna el arcotangente (en radianes) de un number, esto es

+ +

Math.atan(x)=arctan(x)= el único y[-π2;π2] tal quetan(y)=x\mathtt{\operatorname{Math.atan}(x)} = \arctan(x) = \text{ the unique } \; y \in \left[-\frac{\pi}{2}; \frac{\pi}{2}\right] \, \text{such that} \; \tan(y) = x

+ +
{{EmbedInteractiveExample("pages/js/math-atan.html")}}
+ + + +

Sintaxis

+ +
Math.atan(x)
+ +

Parámetros

+ +
+
x
+
Un número.
+
+ +

Valor de retorno

+ +

El arcotangente (en radianes) de el número dado.

+ +

Descripción

+ +

El método Math.atan() retorna un valor numérico entre -π2-\frac{\pi}{2} y π2\frac{\pi}{2} radianes.

+ +

Dado que atan() es un método estático de Math, siempre debes usarlo como Math.atan(), y no como un método de un objeto Math que hayas creado (Math no es un constructor).

+ +

Ejemplos

+ +

Usando Math.atan()

+ +
Math.atan(1);   // 0.7853981633974483
+Math.atan(0);   // 0
+Math.atan(-0);  // -0
+
+Math.atan(Infinity);   //  1.5707963267948966
+Math.atan(-Infinity);  // -1.5707963267948966
+
+// El ángulo que la línea [(0,0);(x,y)] forma con el eje-x en un sistema de coordenadas Cartesianas.
+Math.atan(y / x);
+
+ +

Nota que podrías querer evitar usar ±Infinity por razones de estilo. En este caso, {{jsxref("Math.atan2()")}} con 0 como segundo argumento puede ser una mejor solución.

+ +

Especificaciones

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaciónEstadoComentario
{{SpecName('ES1')}}{{Spec2('ES1')}}Definición inicial. Implementada en JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.8.2.4', 'Math.atan')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math.atan', 'Math.atan')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-math.atan', 'Math.atan')}}{{Spec2('ESDraft')}} 
+ +

Compatibilidad con el navegador

+ + + +

{{Compat("javascript.builtins.Math.atan")}}

+ +

Ver también

+ + diff --git a/files/es/web/javascript/reference/global_objects/math/atan2/index.html b/files/es/web/javascript/reference/global_objects/math/atan2/index.html new file mode 100644 index 0000000000..7b0dc147da --- /dev/null +++ b/files/es/web/javascript/reference/global_objects/math/atan2/index.html @@ -0,0 +1,141 @@ +--- +title: Math.atan2() +slug: Web/JavaScript/Referencia/Objetos_globales/Math/atan2 +translation_of: Web/JavaScript/Reference/Global_Objects/Math/atan2 +--- +
{{JSRef("Global_Objects", "Math")}}
+ +

Resumen

+ +

La función Math.atan2() retorna la arcotangente del cociente de los argumentos.

+ +

Sintaxis

+ +
Math.atan2(y, x)
+ +

Parámetros

+ +
+
y
+
Primer número.
+
x
+
Segundo número.
+
+ +

Descripción

+ +

El método Math.atan2() retorna un valor númerico entre -π y π representando el ángulo theta de un punto (x, y). Este es un ángulo en sentido antihorario, medido en radianes, entre el eje positivo X, y el punto (x, y). Tenga en cuenta que esta función recibe la coordenada Y como primer argumento y X como segundo.

+ +

A la función Math.atan2() se  le pasan los argumentos x y y por separado, y a Math.atan() se le pasa la relación de los dos argumentos.

+ +

Debido a que  atan2() es un método estatico de Math, siempre se debe usar Math.atan2(), en vez de usarlo como un método creado por el objeto Math (Math no es un contructor).

+ +

Ejemplos

+ +

Ejemplo: Usando Math.atan2()

+ +
Math.atan2(90, 15); // 1.4056476493802699
+Math.atan2(15, 90); // 0.16514867741462683
+
+Math.atan2(±0, -0);               // ±PI.
+Math.atan2(±0, +0);               // ±0.
+Math.atan2(±0, -x);               // ±PI for x > 0.
+Math.atan2(±0, x);                // ±0 for x > 0.
+Math.atan2(-y, ±0);               // -PI/2 for y > 0.
+Math.atan2(y, ±0);                // PI/2 for y > 0.
+Math.atan2(±y, -Infinity);        // ±PI for finite y > 0.
+Math.atan2(±y, +Infinity);        // ±0 for finite y > 0.
+Math.atan2(±Infinity, x);         // ±PI/2 for finite x.
+Math.atan2(±Infinity, -Infinity); // ±3*PI/4.
+Math.atan2(±Infinity, +Infinity); // ±PI/4.
+
+ +

Especificaciones

+ + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaciónEstadoComentario
ECMAScript 1st Edition.StandardInitial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.8.2.5', 'Math.atan2')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math.atan2', 'Math.atan2')}}{{Spec2('ES6')}} 
+ +

Compatibilidad con navegadores

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Ver también

+ + diff --git a/files/es/web/javascript/reference/global_objects/math/atanh/index.html b/files/es/web/javascript/reference/global_objects/math/atanh/index.html new file mode 100644 index 0000000000..85022b4138 --- /dev/null +++ b/files/es/web/javascript/reference/global_objects/math/atanh/index.html @@ -0,0 +1,87 @@ +--- +title: Math.atanh() +slug: Web/JavaScript/Referencia/Objetos_globales/Math/atanh +translation_of: Web/JavaScript/Reference/Global_Objects/Math/atanh +--- +
{{JSRef}}
+ +

La función Math.atanh() nos retorna un arco hiperbólico de un numero, eso es:

+ +

x(-1,1),Math.atanh(x)=arctanh(x)= the unique ysuch thattanh(y)=x\forall x \in \left( -1, 1 \right), \mathtt{\operatorname{Math.atanh}(x)} = \operatorname{arctanh}(x) = \text{ el unico } \; y \; \text{de tal manera que} \; \tanh(y) = x

+ +
{{EmbedInteractiveExample("pages/js/math-atanh.html")}}
+ + + +

Sintaxis

+ +
Math.atanh(x)
+ +

Parametros

+ +
+
x
+
Un numero.
+
+ +

Retorna un valor

+ +

El arco hiperbolico tangible nos otorga un numero.

+ +

Descripción

+ +

Por que atanh() es un metodo estatico de Math, tu siempre puedes usar eso como Math.atanh(), se puede usar como un metod de Math objeto que tu creaste (Math no es un constructor).

+ +

Polimorfismo

+ +

Para |x|<1\left|x\right| < 1, tenemos artanh(x)=12ln(1+x1-x)\operatorname {artanh} (x) = \frac{1}{2}\ln \left( \frac{1 + x}{1 - x} \right) por lo que esto puede estar emulado con la siguiente función:

+ +
Math.atanh = Math.atanh || function(x) {
+  return Math.log((1+x)/(1-x)) / 2;
+};
+
+ +

Ejemplos

+ +

Using Math.atanh()

+ +
Math.atanh(-2);  // NaN
+Math.atanh(-1);  // -Infinito
+Math.atanh(0);   // 0
+Math.atanh(0.5); // 0.5493061443340548
+Math.atanh(1);   // Infinito
+Math.atanh(2);   // NaN
+
+ +

Para valores mayores a 1 o menores a -1, {{jsxref("NaN")}} retorna.

+ +

Especificaciones

+ + + + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-math.atanh', 'Math.atanh')}}
+ +

Compatibilidad entre navegadores

+ + + +

{{Compat("javascript.builtins.Math.atanh")}}

+ +

Puedes leer

+ + diff --git a/files/es/web/javascript/reference/global_objects/math/cbrt/index.html b/files/es/web/javascript/reference/global_objects/math/cbrt/index.html new file mode 100644 index 0000000000..350bc03054 --- /dev/null +++ b/files/es/web/javascript/reference/global_objects/math/cbrt/index.html @@ -0,0 +1,96 @@ +--- +title: Math.cbrt() +slug: Web/JavaScript/Referencia/Objetos_globales/Math/cbrt +translation_of: Web/JavaScript/Reference/Global_Objects/Math/cbrt +--- +
{{JSRef}}
+ +

La función Math.cbrt() nos retorna la raíz del cubo del numero, eso es

+ +

Math.cbrt(x)=x3=the uniqueysuch thaty3=x\mathtt{Math.cbrt(x)} = \sqrt[3]{x} = \text{un unico} \; y \; \text{de tal manera que} \; y^3 = x

+ +
{{EmbedInteractiveExample("pages/js/math-cbrt.html")}}
+ + + +

Sintaxis

+ +
Math.cbrt(x)
+ +

Parametros

+ +
+
x
+
Un numero
+
+ +

Valor retornado

+ +

La raíz cubica del numero proporcionado

+ +

Descripción

+ +

Al cbrt() ser un metodo estatico de Math, tu siempre la puedes usar como Math.cbrt(),un metodo de Math que es un objeto que se crea (Math no es un constructor).

+ +

Poliformismo

+ +

Para x0x \geq 0, tenemos x3=x1/3\sqrt[3]{x} = x^{1/3} esto puede ser emulado con la siguiente función:

+ +
if (!Math.cbrt) {
+  Math.cbrt = (function(pow) {
+    return function cbrt(x){
+      // Esto asegura que numeros negativos sigan siendo negativos
+      return x < 0 ? -pow(-x, 1/3) : pow(x, 1/3);
+    };
+  })(Math.pow); // Localiza Math.pow para una mayor eficiencía
+}
+
+ +

Ejemplos

+ +

Usando Math.cbrt()

+ +
Math.cbrt(NaN); // NaN
+Math.cbrt(-1); // -1
+Math.cbrt(-0); // -0
+Math.cbrt(-Infinity); // -Infinito
+Math.cbrt(0); // 0
+Math.cbrt(1); // 1
+Math.cbrt(Infinity); // Infinito
+Math.cbrt(null); // 0
+Math.cbrt(2);  // 1.2599210498948732
+
+ +

Especificaciones

+ + + + + + + + + + + + +
Especificación
{{SpecName('ESDraft', '#sec-math.cbrt', 'Math.cbrt')}}
+ +

Compatibilidad

+ + + + + +

and send us a pull request.

+ +

{{Compat("javascript.builtins.Math.cbrt")}}

+ +

Puedes leer

+ + diff --git a/files/es/web/javascript/reference/global_objects/math/ceil/index.html b/files/es/web/javascript/reference/global_objects/math/ceil/index.html new file mode 100644 index 0000000000..52b43cd3a2 --- /dev/null +++ b/files/es/web/javascript/reference/global_objects/math/ceil/index.html @@ -0,0 +1,166 @@ +--- +title: Math.ceil() +slug: Web/JavaScript/Referencia/Objetos_globales/Math/ceil +tags: + - JavaScript + - Math + - Referencia + - metodo +translation_of: Web/JavaScript/Reference/Global_Objects/Math/ceil +--- +
{{JSRef}}
+ +

La función Math.ceil() devuelve el entero mayor o igual más próximo a un número dado.

+ +
{{EmbedInteractiveExample("pages/js/math-ceil.html")}}
+ +

Sintaxis

+ +
Math.ceil(x)
+ +

Parámetros

+ +
+
x
+
Un número.
+
+ +

Valor devuelto

+ +

El número entero mayor o igual más próximo que el número dado.

+ +

Descripción

+ +

Como ceil() es un método estático de Math, siempre debe usarlo como Math.ceil(), en lugar de como un método de un objeto que ha creado Math (Math no es un constructor).

+ +

Ejemplos

+ +

Utilizando Math.ceil()

+ +

El siguiente ejemplo muestra el uso de Math.ceil().

+ +
Math.ceil(.95);    // 1
+Math.ceil(4);      // 4
+Math.ceil(7.004);  // 8
+Math.ceil(-0.95);  // -0
+Math.ceil(-4);     // -4
+Math.ceil(-7.004); // -7
+
+ +

Ajuste decimal

+ +
// Closure
+(function() {
+  /**
+   * Ajuste decimal de un número.
+   *
+   * @param {String}  type  El tipo de ajuste.
+   * @param {Number}  value El número.
+   * @param {Integer} exp   El exponente (El logaritmo de ajuste en base 10).
+   * @returns {Number} El valor ajustado.
+   */
+  function decimalAdjust(type, value, exp) {
+    // Si exp es undefined o cero...
+    if (typeof exp === 'undefined' || +exp === 0) {
+      return Math[type](value);
+    }
+    value = +value;
+    exp = +exp;
+    // Si el valor no es un número o exp no es un entero...
+    if (isNaN(value) || !(typeof exp === 'number' && exp % 1 === 0)) {
+      return NaN;
+    }
+    // Shift
+    value = value.toString().split('e');
+    value = Math[type](+(value[0] + 'e' + (value[1] ? (+value[1] - exp) : -exp)));
+    // Shift back
+    value = value.toString().split('e');
+    return +(value[0] + 'e' + (value[1] ? (+value[1] + exp) : exp));
+  }
+
+  // Decimal round
+  if (!Math.round10) {
+    Math.round10 = function(value, exp) {
+      return decimalAdjust('round', value, exp);
+    };
+  }
+  // Decimal floor
+  if (!Math.floor10) {
+    Math.floor10 = function(value, exp) {
+      return decimalAdjust('floor', value, exp);
+    };
+  }
+  // Decimal ceil
+  if (!Math.ceil10) {
+    Math.ceil10 = function(value, exp) {
+      return decimalAdjust('ceil', value, exp);
+    };
+  }
+})();
+
+// Round
+Math.round10(55.55, -1);   // 55.6
+Math.round10(55.549, -1);  // 55.5
+Math.round10(55, 1);       // 60
+Math.round10(54.9, 1);     // 50
+Math.round10(-55.55, -1);  // -55.5
+Math.round10(-55.551, -1); // -55.6
+Math.round10(-55, 1);      // -50
+Math.round10(-55.1, 1);    // -60
+// Floor
+Math.floor10(55.59, -1);   // 55.5
+Math.floor10(59, 1);       // 50
+Math.floor10(-55.51, -1);  // -55.6
+Math.floor10(-51, 1);      // -60
+// Ceil
+Math.ceil10(55.51, -1);    // 55.6
+Math.ceil10(51, 1);        // 60
+Math.ceil10(-55.59, -1);   // -55.5
+Math.ceil10(-59, 1);       // -50
+
+ +

Espicificaciones

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaciónEstadoComentario
{{SpecName('ES1')}}{{Spec2('ES1')}}Definición inicial. Implementado en JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.8.2.6', 'Math.ceil')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-math.ceil', 'Math.ceil')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-math.ceil', 'Math.ceil')}}{{Spec2('ESDraft')}}
+ +

Compatibilidad en navegadores

+ +

{{Compat("javascript.builtins.Math.ceil")}}

+ +

Ver también

+ + diff --git a/files/es/web/javascript/reference/global_objects/math/cos/index.html b/files/es/web/javascript/reference/global_objects/math/cos/index.html new file mode 100644 index 0000000000..82a0793769 --- /dev/null +++ b/files/es/web/javascript/reference/global_objects/math/cos/index.html @@ -0,0 +1,74 @@ +--- +title: Math.cos() +slug: Web/JavaScript/Referencia/Objetos_globales/Math/cos +translation_of: Web/JavaScript/Reference/Global_Objects/Math/cos +--- +
{{JSRef}}
+ +

La función estática Math.cos() devuelve el coseno del ángulo especificado, que debe ser especificado en radianes. Este valor es longitud adyacente longitud hipotenusa .

+ +
{{EmbedInteractiveExample("pages/js/math-cos.html")}}
+ + + +

Sintaxis

+ +
Math.cos(x)
+ +

Parametros

+ +
+
x
+
El ángulo en radianes por el cual devolverá el coseno.
+
+ +

Valor de retorno

+ +

El coseno del número dado.

+ +

Descripción

+ +

El método Math.cos() retorna un valor numérico entre -1 y 1, que representa el coseno del ángulo.

+ +

Debido a que cos() es un método estático de Math, siempre debes utilizarlo como Math.cos(), en lugar de como un método de un objeto Math que hayas creado (Math no es un constructor).

+ +

Ejemplos

+ +

Usando Math.cos()

+ +
Math.cos(0);           // 1
+Math.cos(1);           // 0.5403023058681398
+
+Math.cos(Math.PI);     // -1
+Math.cos(2 * Math.PI); // 1
+
+ +

Especificaciones

+ + + + + + + + + + +
Especificación
{{SpecName('ESDraft', '#sec-math.cos', 'Math.cos')}}
+ +

Compatibilidad de navegadores

+ + + +

{{Compat("javascript.builtins.Math.cos")}}

+ +

Ver también

+ + diff --git a/files/es/web/javascript/reference/global_objects/math/e/index.html b/files/es/web/javascript/reference/global_objects/math/e/index.html new file mode 100644 index 0000000000..2fdc92d125 --- /dev/null +++ b/files/es/web/javascript/reference/global_objects/math/e/index.html @@ -0,0 +1,83 @@ +--- +title: Math.E +slug: Web/JavaScript/Referencia/Objetos_globales/Math/E +tags: + - JavaScript + - Math + - Property + - Referencia +translation_of: Web/JavaScript/Reference/Global_Objects/Math/E +--- +
{{JSRef}}
+ +

La propiedad Math.E representa la base de los logaritmos naturales, e, aproximadamente 2.718.

+ +

Math.E=e2.718\mathtt{\mi{Math.E}} = e \approx 2.718

+ +

{{EmbedInteractiveExample("pages/js/math-e.html")}}

+ +
{{js_property_attributes(0, 0, 0)}}
+ +

Descripción

+ +

Porque E es una propiedad estática de Math, siempre usted lo usa como Math.E, en lugar de como una propiedad de un objeto Math creado (Math no es un constructor).

+ +

Ejemplos

+ +

Utilizando Math.E

+ +

La función siguiente devuelve e:

+ +
function getNapier() {
+   return Math.E
+}
+
+getNapier(); // 2.718281828459045
+ +

 

+ +

Especificaciones

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaciónEstadoComentario
{{SpecName('ES1')}}{{Spec2('ES1')}}Definición inicial. Implementado en JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.8.1.1', 'Math.E')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math.e', 'Math.E')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-math.e', 'Math.E')}}{{Spec2('ESDraft')}} 
+ +

Compatibilidad con navegadores

+ +

{{Compat("javascript.builtins.Math.E")}}

+ +

 

+ +

Ver también

+ + diff --git a/files/es/web/javascript/reference/global_objects/math/exp/index.html b/files/es/web/javascript/reference/global_objects/math/exp/index.html new file mode 100644 index 0000000000..ca60758600 --- /dev/null +++ b/files/es/web/javascript/reference/global_objects/math/exp/index.html @@ -0,0 +1,136 @@ +--- +title: Math.exp() +slug: Web/JavaScript/Referencia/Objetos_globales/Math/exp +translation_of: Web/JavaScript/Reference/Global_Objects/Math/exp +--- +
{{JSRef}}
+ +
La función Math.exp() devuelve ex, donde x es el argumento, y e es {{jsxref("Math.E", "El número de Euler (también conocido como la constante de Napier)", "", 1)}}, la base de los algoritmos naturales.
+ +
 
+ +

Sintaxis

+ +
Math.exp(x)
+ +

Parámetros

+ +
+
x
+
Un número.
+
+ +

Valor devuelto

+ +

Un número represetando ex, donde e es {{jsxref("Math.E", "número de Euler", "", 1)}} y x es el argumento.

+ +

Descripción

+ +

Porque exp() es un método estático de Math, siempre úsalo como Math.exp(), en vez de un método de un objeto Math que hayas creado (Math no es un constructor).

+ +

Ejemplos

+ +

Usando Math.exp()

+ +
Math.exp(-1); // 0.36787944117144233
+Math.exp(0);  // 1
+Math.exp(1);  // 2.718281828459045
+
+ +

Especificaciones

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaciónEstadoComentario
{{SpecName('ES1')}}{{Spec2('ES1')}} +

Definición inicial. Implementado en JavaScript 1.0.

+
{{SpecName('ES5.1', '#sec-15.8.2.8', 'Math.exp')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math.exp', 'Math.exp')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-math.exp', 'Math.exp')}}{{Spec2('ESDraft')}} 
+ +

Compatibilidad con navegadores

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari
Soporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidChrome para AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Soporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Ve también

+ + diff --git a/files/es/web/javascript/reference/global_objects/math/expm1/index.html b/files/es/web/javascript/reference/global_objects/math/expm1/index.html new file mode 100644 index 0000000000..d8679d9230 --- /dev/null +++ b/files/es/web/javascript/reference/global_objects/math/expm1/index.html @@ -0,0 +1,89 @@ +--- +title: Math.expm1() +slug: Web/JavaScript/Referencia/Objetos_globales/Math/expm1 +tags: + - JavaScript + - Matemáticas + - Math + - Method + - Referencia + - metodo +translation_of: Web/JavaScript/Reference/Global_Objects/Math/expm1 +--- +
{{JSRef}}
+ +

La función Math.expm1() regresa ex - 1, donde x es el argumento, y {{jsxref("Math.E", "e", "", 1)}} la base del logaritmo natural.

+ +
{{EmbedInteractiveExample("pages/js/math-expm1.html")}}
+ + + +

Sintaxis

+ +
Math.expm1(x)
+ +

Parámetos

+ +
+
x
+
Un número.
+
+ +

Valor de retorno

+ +

Un número representando ex - 1, donde e es {{jsxref("Math.E", "Número de Euler", "", 1)}} y  x es el argumento.

+ +

Descripción

+ +

Debido a que expm1() es un método estático de Math, uselo siempre como Math.expm1(), en lugar de como un método del objeto Math que creó (Math no es un constructor).

+ +

Ejemplos

+ +

Usando Math.expm1()

+ +
Math.expm1(-1); // -0.6321205588285577
+Math.expm1(0);  // 0
+Math.expm1(1);  // 1.718281828459045
+
+ +

Polyfill

+ +

Esto puede ser emulado con la ayuda de la función {{jsxref("Math.exp()")}}:

+ +
Math.expm1 = Math.expm1 || function(x) {
+  return Math.exp(x) - 1;
+};
+
+ +

Especificaciones

+ + + + + + + + + + + + +
Especificación
{{SpecName('ESDraft', '#sec-math.expm1', 'Math.expm1')}}
+ +

Compatibilidad de navegadores

+ + + +

{{Compat("javascript.builtins.Math.expm1")}}

+ +

Vea también

+ + diff --git a/files/es/web/javascript/reference/global_objects/math/floor/index.html b/files/es/web/javascript/reference/global_objects/math/floor/index.html new file mode 100644 index 0000000000..867f3e8dac --- /dev/null +++ b/files/es/web/javascript/reference/global_objects/math/floor/index.html @@ -0,0 +1,124 @@ +--- +title: Math.floor() +slug: Web/JavaScript/Referencia/Objetos_globales/Math/floor +tags: + - JavaScript + - Math + - Method +translation_of: Web/JavaScript/Reference/Global_Objects/Math/floor +--- +
{{JSRef("Objetos_globales", "Math")}}
+ +

Sumario

+ +

Devuelve el máximo entero menor o igual a un número.

+ +

Sintaxis

+ +
Math.floor(x) 
+ +

Parámetros

+ +
+
x
+
Es número.
+
+ +

Descripción

+ +

Como floor es un método estático de Math, siempre debe usarse como Math.floor(), en lugar de usarlo como un método de un objeto Math creado.

+ +

Ejemplos

+ +

Ejemplo: Usando Math.floor

+ +

La siguiente función devuelve el valor entero redondeado más bajo de la variable x:

+ +
function getFloor(x) {
+   return Math.floor(x);
+}
+ +

Si se pasa 45.95 a getFloor, éste devuelve 45; si se le pasa -45.95,  devuelve -46.

+ +

Ejemplo: Ajuste decimal

+ +
// Cierre
+(function(){
+
+	/**
+	 * Ajuste decimal de un número.
+	 *
+	 * @param	{String}	type	El tipo de ajuste.
+	 * @param	{Number}	value	El número.
+	 * @param	{Integer}	exp		El exponente(el logaritmo en base 10 del ajuste).
+	 * @returns	{Number}			El valor ajustado.
+	 */
+	function decimalAdjust(type, value, exp) {
+		// Si el exp es indefinido o cero...
+		if (typeof exp === 'undefined' || +exp === 0) {
+			return Math[type](value);
+		}
+		value = +value;
+		exp = +exp;
+		// Si el valor no es un número o el exp no es un entero...
+		if (isNaN(value) || !(typeof exp === 'number' && exp % 1 === 0)) {
+			return NaN;
+		}
+		// Cambio
+		value = value.toString().split('e');
+		value = Math[type](+(value[0] + 'e' + (value[1] ? (+value[1] - exp) : -exp)));
+		// Volver a cambiar
+		value = value.toString().split('e');
+		return +(value[0] + 'e' + (value[1] ? (+value[1] + exp) : exp));
+	}
+
+	// Redondeo decimal
+	if (!Math.round10) {
+		Math.round10 = function(value, exp) {
+			return decimalAdjust('round', value, exp);
+		};
+	}
+	// Redondeo hacia abajo
+	if (!Math.floor10) {
+		Math.floor10 = function(value, exp) {
+			return decimalAdjust('floor', value, exp);
+		};
+	}
+	// Redondeo hacia arriba
+	if (!Math.ceil10) {
+		Math.ceil10 = function(value, exp) {
+			return decimalAdjust('ceil', value, exp);
+		};
+	}
+
+})();
+
+// Redondeo
+Math.round10(55.55, -1); // 55.6
+Math.round10(55.549, -1); // 55.5
+Math.round10(55, 1); // 60
+Math.round10(54.9, 1); // 50
+Math.round10(-55.55, -1); // -55.5
+Math.round10(-55.551, -1); // -55.6
+Math.round10(-55, 1); // -50
+Math.round10(-55.1, 1); // -60
+// Piso
+Math.floor10(55.59, -1); // 55.5
+Math.floor10(59, 1); // 50
+Math.floor10(-55.51, -1); // -55.6
+Math.floor10(-51, 1); // -60
+// Techo
+Math.ceil10(55.51, -1); // 55.6
+Math.ceil10(51, 1); // 60
+Math.ceil10(-55.59, -1); // -55.5
+Math.ceil10(-59, 1); // -50
+
+ +

Ven También

+ + diff --git a/files/es/web/javascript/reference/global_objects/math/fround/index.html b/files/es/web/javascript/reference/global_objects/math/fround/index.html new file mode 100644 index 0000000000..73d773e5b0 --- /dev/null +++ b/files/es/web/javascript/reference/global_objects/math/fround/index.html @@ -0,0 +1,199 @@ +--- +title: Math.fround() +slug: Web/JavaScript/Referencia/Objetos_globales/Math/fround +tags: + - JavaScript + - Math + - Referencia + - metodo +translation_of: Web/JavaScript/Reference/Global_Objects/Math/fround +--- +
{{JSRef}}
+ +

The Math.fround() function returns the nearest 32-bit single precision float representation of a {{jsxref("Number")}}.

+ +
{{EmbedInteractiveExample("pages/js/math-fround.html")}}
+ + + +

Syntax

+ +
var singleFloat = Math.fround(doubleFloat);
+ +

Parameters

+ +
+
doubleFloat
+
A {{jsxref("Number")}}. If the parameter is of a different type, it will get converted to a number or to {{jsxref("NaN")}} if it cannot be converted.
+
+ +

Return value

+ +

The nearest 32-bit single precision float representation of the given number.

+ +

Description

+ +

JavaScript uses 64-bit double floating-point numbers internally, which offer a very high precision. However, sometimes you may be working with 32-bit floating-point numbers, for example if you are reading values from a {{jsxref("Float32Array")}}. This can create confusion: Checking a 64-bit float and a 32-bit float for equality may fail even though the numbers are seemingly identical.

+ +

To solve this, Math.fround() can be used to cast the 64-bit float to a 32-bit float. Internally, JavaScript continues to treat the number as a 64-bit float, it just performs a "round to even" on the 23rd bit of the mantissa, and sets all following mantissa bits to 0. If the number is outside the range of a 32-bit float, {{jsxref("Infinity")}} or -Infinity is returned.

+ +

Because fround() is a static method of Math, you always use it as Math.fround(), rather than as a method of a Math object you created (Math is not a constructor).

+ +

Examples

+ +

Using Math.fround()

+ +

The number 1.5 can be precisely represented in the binary numeral system, and is identical in 32-bit and 64-bit:

+ +
Math.fround(1.5); // 1.5
+Math.fround(1.5) === 1.5; // true
+
+ +

However, the number 1.337 cannot be precisely represented in the binary numeral system, so it differs in 32-bit and 64-bit:

+ +
Math.fround(1.337); // 1.3370000123977661
+Math.fround(1.337) === 1.337; // false
+
+ +

21502^150 is too big for a 32-bit float, so Infinity is returned:

+ +
2 ** 150; // 1.42724769270596e+45
+Math.fround(2 ** 150); // Infinity
+
+ +

If the parameter cannot be converted to a number, or it is not-a-number (NaN), Math.fround() will return NaN:

+ +
Math.fround('abc'); // NaN
+Math.fround(NaN); // NaN
+
+ +

Polyfill

+ +

This can be emulated with the following function, if {{jsxref("Float32Array")}} are supported:

+ +
Math.fround = Math.fround || (function (array) {
+  return function(x) {
+    return array[0] = x, array[0];
+  };
+})(new Float32Array(1));
+
+ +

Supporting older browsers is slower, but also possible:

+ +
if (!Math.fround) Math.fround = function(arg) {
+  arg = Number(arg);
+  // Return early for ±0 and NaN.
+  if (!arg) return arg;
+  var sign = arg < 0 ? -1 : 1;
+  if (sign < 0) arg = -arg;
+  // Compute the exponent (8 bits, signed).
+  var exp = Math.floor(Math.log(arg) / Math.LN2);
+  var powexp = Math.pow(2, Math.max(-126, Math.min(exp, 127)));
+  // Handle subnormals: leading digit is zero if exponent bits are all zero.
+  var leading = exp < -127 ? 0 : 1;
+  // Compute 23 bits of mantissa, inverted to round toward zero.
+  var mantissa = Math.round((leading - arg / powexp) * 0x800000);
+  if (mantissa <= -0x800000) return sign * Infinity;
+  return sign * powexp * (leading - mantissa / 0x800000);
+};
+ +

Faster Alternative Polyfill (Work In Progress)

+ +

The below polyfill is much faster and uses double-precision rounding errors to emulate the rounding errors caused by floating point narrowing. Although the polyfill higher on the page is good for comprehension, all of the complex Math function that it uses make it terrible slow. Although this polyfill is much faster, it is off by a bit in about 1 out of 2048 of the tests due to the tendency to round upwards like Math.ceil instead of like Math.round in the division of the subnormal-handling section of the code. Because single precision floating points have 23 bits of precision, the mean error deviation from the correct value is roughly 2**-28 or 0.0000000058%. This deviation from the correct value should be insignifigant in most circumstances, however please edit this polyfill if you have some tweaks to increase correctness without bloating the code size too much. NaN is not optimized for because it is most likely (almost certain) that you will not be calling Math.fround with NaN exclusively in a tight loop. Moreover, an additional check just for NaN instead of letting NaN naturally arise would induce a performance penalty for this function in older browsers when not called with NaN. Thus, the code below handles NaN correctly, but inefficiently for good reason.

+ +
const Math_round = Math.round;
+if (!Math.fround) Math.fround = function(x) {
+    if (x > 3.402823669209385e+38) return Infinity; // maximum float is 2**128
+    if (x < -3.402823669209385e+38) return -Infinity; // minimum is -2**128
+    if (-1.1754943508222875e-38 < x && x < 1.1754943508222875e-38) {
+        if (-1.401298464324817e-45 < x && x < 1.401298464324817e-45) return 0;
+        // else, it is a subnormal
+        var mul = Math_round(x/1.4012984643e-45)*1e-323;
+        return mul * 1.418129833677085e+278;
+    }
+
+    var hi = x * 9007199254740992; // 9007199254740992 is 2**53 which is the maximum of double precision
+    var exp = (x + hi) - hi; // adding this number chops off all lower bits, rounding the number.
+    exp /= 16777216; // 8388608 = 2**23 * 2, so preserve 23 bits in x because there are 23 bits in a float
+                     //            The "* 2" compensates for the addition shifting up the bits unwantedly
+    return Math_round(x / exp) * exp;
+}
+
+ +

Below is code used to test for deviations from the correct value. The code below is meant for testing the merit of the function, not for polyfilling older browsers (as evidenced by the fact that the native Math.fround function is used).

+ +
requestIdleCallback(function(){"use strict";
+    const Math_fround = Math.fround;
+    const Math_round = Math.round;
+    function my_fround(x) {
+        if (x > 3.402823669209385e+38) return Infinity; // maximum float is 2**128
+        if (x < -3.402823669209385e+38) return -Infinity; // minimum is -2**128
+        if (-1.1754943508222875e-38 < x && x < 1.1754943508222875e-38) {
+            if (-1.401298464324817e-45 < x && x < 1.401298464324817e-45) return 0;
+            // else, it is a subnormal
+            var mul = Math_round(x/1.4012984643e-45)*1e-323;
+            return mul * 1.418129833677085e+278;
+        }
+
+        var hi = x * 9007199254740992; // 9007199254740992 is 2**53 which is the maximum of double precision
+        var exp = (x + hi) - hi; // adding this number chops off all lower bits, rounding the number.
+        exp /= 16777216; // 8388608 = 2**23 * 2, so preserve 23 bits in x because there are 23 bits in a float
+                         //            The "* 2" compensates for the addition shifting up the bits unwantedly
+        return Math_round(x / exp) * exp;
+    }
+
+    const doublesArray = new Float64Array(8192);
+    const int32s = new Uint32Array(doublesArray.buffer);
+
+    const crypto = window.crypto;
+
+    var hasWarned = false, warnings=0;
+    for (var i=0; i<4; i=i+1|0) {
+        crypto.getRandomValues(int32s);
+        for (var k=0; k<8192; k=k+1|0) {
+            const myValue = my_fround(doublesArray[k]);
+            const froundVal = Math_fround(doublesArray[k]);
+            // quicker version of Object.is because of no function call overhead:
+            if (myValue === myValue ? myValue !== froundVal : froundVal === froundVal) {
+                if (!hasWarned) console.error(doublesArray[k]); // only show the first incorrect number
+                hasWarned = true;
+                warnings = warnings + 1|0;
+            }
+        }
+    }
+    console[warnings > 0 ? "warn" : "log"]( "Total number of mishandled floats: " + warnings );
+});
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES6', '#sec-math.fround', 'Math.fround')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-math.fround', 'Math.fround')}}{{Spec2('ESDraft')}}
+ +

Browser compatibility

+ + + +

{{Compat("javascript.builtins.Math.fround")}}

+ +

See also

+ + diff --git a/files/es/web/javascript/reference/global_objects/math/hypot/index.html b/files/es/web/javascript/reference/global_objects/math/hypot/index.html new file mode 100644 index 0000000000..21d6850e44 --- /dev/null +++ b/files/es/web/javascript/reference/global_objects/math/hypot/index.html @@ -0,0 +1,124 @@ +--- +title: Math.hypot() +slug: Web/JavaScript/Referencia/Objetos_globales/Math/hypot +tags: + - JavaScript + - Math +translation_of: Web/JavaScript/Reference/Global_Objects/Math/hypot +--- +
{{JSRef}}
+ +

La función Math.hypot() retorna la raíz cuadrada de la suma de los cuadrados de sus argumentos, es decir:

+ +

Math.hypot(v1,v2,,vn)=i=1nvi2=v12+v22++vn2\mathtt{\operatorname{Math.hypot}(v_1, v_2, \dots, v_n)} = \sqrt{\sum_{i=1}^n v_i^2} = \sqrt{v_1^2 + v_2^2 + \dots + v_n^2}

+ +
{{EmbedInteractiveExample("pages/js/math-hypot.html")}}
+ + + +

Sintaxis

+ +
Math.hypot(valor1, valor2, ..., valorN)
+ +

Parámetros

+ +
+
Valor1, Valor2, ...
+
Números.
+
+ +

Valor de Retorno

+ +

La raíz cuadrada de la suma de los cuadrados de los argumentos proporcionados. Si tan sólo uno de los argumentos no pudiese ser convertido a un número, se retornaría {{jsxref("NaN")}}.

+ +

Descripción

+ +

Para calcular la hipotenusa de un triángulo rectángulo, o la magnitud de un número complejo, se usa el Teorema de Pitágoras, representado en la siguiente fórmula Math.sqrt(v1*v1 + v2*v2) donde v1 y v2 son, o los catetos del triángulo, o los valores reales y complejos usados para hallar la mencionada magnitud. Para calcular distancias de dos o más dimensiones, simplemente añade más valores al cuadrado (multiplicado por sí mismo) dentro de el método sqrt() del objeto Math, algo como: Math.sqrt(v1*v1 + v2*v2 + v3*v3 + v4*v4).  

+ +

Esta función lo hace un poco más fácil y rápido, sólo coloca: Math.hypot(v1, v2) , o Math.hypot(v1, v2, v3, v4, ...) .  

+ +

Esto también evita un problema si la magnitud de tus números es muy elevada. El número más largo que puedes representar en JavaScript es Number.MAX_VALUE = 1.797...e+308 .  Si tus números son mayores que 1e154, tomando el cuadrado de esos valores resultaría en infinito destruyendo así tus resultados. Por ejemplo, Math.sqrt(1e200*1e200 + 1e200*1e200) = Infinito. Si usas hypot() en su lugar, tú obtendrías un buen resultado Math.hypot(1e200, 1e200) = 1.4142...e+200 .  Eso también es verdad con números demasiados pequeños.  Math.sqrt(1e-200*1e-200 + 1e-200*1e-200) = 0, pero si en su lugar, usamos Math.hypot(1e-200, 1e-200) =1.4142...e-200, obtendríamos un buen resultado una vez más.

+ +

Debido a que hypot() es un método estático de Math, siempre úsalo como Math.hypot(), en lugar de un método del objeto Math que hayas creado (Math no es un constructor).

+ +

Si ningún argumento es provisto, el resultado es 0.

+ +

Con sólo un argumento, Math.hypot() retornaría lo mismo que Math.abs().

+ +

Ejemplos

+ +

Usando Math.hypot()

+ +
Math.hypot(3, 4);        // 5
+Math.hypot(3, 4, 5);     // 7.0710678118654755
+Math.hypot();            // 0
+Math.hypot(NaN);         // NaN
+Math.hypot(3, 4, 'foo'); // NaN, +'foo' => NaN
+Math.hypot(3, 4, '5');   // 7.0710678118654755, +'5' => 5
+Math.hypot(-3);          // 3, lo mismo que Math.abs(-3)
+
+ +

Polyfill

+ +

Esto puede ser emulado usando la siguiente función:

+ +
Math.hypot = Math.hypot || function() {
+  var y = 0, i = arguments.length;
+  while (i--) y += arguments[i] * arguments[i];
+  return Math.sqrt(y);
+};
+
+ +

Un polyfill que evita subdesbordamientos (underflows) y desbordamientos (overflows):

+ +
Math.hypot = function (x, y) {
+  // https://bugzilla.mozilla.org/show_bug.cgi?id=896264#c28
+  var max = 0;
+  var s = 0;
+  for (var i = 0; i < arguments.length; i += 1) {
+    var arg = Math.abs(Number(arguments[i]));
+    if (arg > max) {
+      s *= (max / arg) * (max / arg);
+      max = arg;
+    }
+    s += arg === 0 && max === 0 ? 0 : (arg / max) * (arg / max);
+  }
+  return max === 1 / 0 ? 1 / 0 : max * Math.sqrt(s);
+};
+
+ +

Especificaciones

+ + + + + + + + + + + + + + + + + + + +
EspecificaciónEstadoComentario
{{SpecName('ES2015', '#sec-math.hypot', 'Math.hypot')}}{{Spec2('ES2015')}}Definición inicial.
{{SpecName('ESDraft', '#sec-math.hypot', 'Math.hypot')}}{{Spec2('ESDraft')}} 
+ +

Compatibilidad en navegadores

+ + + +

{{Compat("javascript.builtins.Math.hypot")}}

+ +

Ver también

+ + diff --git a/files/es/web/javascript/reference/global_objects/math/index.html b/files/es/web/javascript/reference/global_objects/math/index.html new file mode 100644 index 0000000000..bdf0d21e74 --- /dev/null +++ b/files/es/web/javascript/reference/global_objects/math/index.html @@ -0,0 +1,196 @@ +--- +title: Math +slug: Web/JavaScript/Referencia/Objetos_globales/Math +tags: + - JavaScript + - Math + - Referencia +translation_of: Web/JavaScript/Reference/Global_Objects/Math +--- +
{{JSRef}}
+ +

Math es un objeto incorporado que tiene propiedades y métodos para constantes y funciones matemáticas. No es un objeto de función.

+ +

Math funciona con el tipo {{jsxref("Number")}}. No funciona con {{jsxref("BigInt")}}.

+ +

Descripción

+ +

A diferencia de los demás objetos globales, el objeto Math no se puede editar. Todas las propiedades y métodos de Math son estáticos. Usted se puede referir a la constante pi como Math.PI y puede llamar a la función seno como Math.sin(x), donde x es el argumento del método. Las constantes se definen con la precisión completa de los números reales en JavaScript.

+ +

Propiedades

+ +
+
{{jsxref("Math.E")}}
+
Constante de Euler, la base de los logaritmos naturales, aproximadamente 2.718.
+
{{jsxref("Math.LN2")}}
+
Logaritmo natural de 2, aproximadamente 0.693.
+
{{jsxref("Math.LN10")}}
+
Logaritmo natural de 10, aproximadamente 2.303.
+
{{jsxref("Math.LOG2E")}}
+
Logaritmo de E con base 2, aproximadamente 1.443.
+
{{jsxref("Math.LOG10E")}}
+
Logaritmo de E con base 10, aproximadamente 0.434.
+
{{jsxref("Math.PI")}}
+
Ratio de la circunferencia de un circulo respecto a su diámetro, aproximadamente 3.14159.
+
{{jsxref("Math.SQRT1_2")}}
+
Raíz cuadrada de 1/2; Equivalentemente, 1 sobre la raíz cuadrada de 2, aproximadamente 0.707.
+
{{jsxref("Math.SQRT2")}}
+
Raíz cuadrada de 2, aproximadamente 1.414.
+
+ +

Métodos

+ +
+

Tenga en cuenta que las funciones trigonométricas (sin(), cos(), tan(), asin(), acos(), atan(), atan2()) devuelven ángulos en radianes. Para convertir radianes a grados, divida por (Math.PI / 180), y multiplique por esto para convertir a la inversa.

+
+ +
+

Tenga en cuenta que muchas de las funciones matemáticas tienen una precisión que es dependiente de la implementación. Esto significa que los diferentes navegadores pueden dar un resultado diferente, e incluso el mismo motor de JS en un sistema operativo o arquitectura diferente puede dar resultados diferentes.

+
+ +
+
{{jsxref("Global_Objects/Math/abs", "Math.abs(x)")}}
+
Devuelve el valor absoluto de un número.
+
{{jsxref("Global_Objects/Math/acos", "Math.acos(x)")}}
+
Devuelve el arco coseno de un número.
+
{{jsxref("Global_Objects/Math/acosh", "Math.acosh(x)")}}
+
Devuelve el arco coseno hiperbólico de un número.
+
{{jsxref("Global_Objects/Math/asin", "Math.asin(x)")}}
+
Devuelve el arco seno de un número.
+
{{jsxref("Global_Objects/Math/asinh", "Math.asinh(x)")}}
+
Devuelve el arco seno hiperbólico de un número.
+
{{jsxref("Global_Objects/Math/atan", "Math.atan(x)")}}
+
Devuelve el arco tangente de un número.
+
{{jsxref("Global_Objects/Math/atanh", "Math.atanh(x)")}}
+
Devuelve el arco tangente hiperbólico de un número.
+
{{jsxref("Global_Objects/Math/atan2", "Math.atan2(y, x)")}}
+
Devuelve el arco tangente del cuociente de sus argumentos.
+
{{jsxref("Global_Objects/Math/cbrt", "Math.cbrt(x)")}}
+
Devuelve la raíz cúbica de un número.
+
{{jsxref("Global_Objects/Math/ceil", "Math.ceil(x)")}}
+
Devuelve el entero más pequeño mayor o igual que un número.
+
{{jsxref("Global_Objects/Math/clz32", "Math.clz32(x)")}}
+
Devuelve el número de ceros iniciales de un entero de 32 bits.
+
{{jsxref("Global_Objects/Math/cos", "Math.cos(x)")}}
+
Devuelve el coseno de un número.
+
{{jsxref("Global_Objects/Math/cosh", "Math.cosh(x)")}}
+
Devuelve el coseno hiperbólico de un número.
+
{{jsxref("Global_Objects/Math/exp", "Math.exp(x)")}}
+
Devuelve Ex, donde x es el argumento, y E es la constante de Euler (2.718...), la base de los logaritmos naturales.
+
{{jsxref("Global_Objects/Math/expm1", "Math.expm1(x)")}}
+
Devuelve ex - 1.
+
{{jsxref("Global_Objects/Math/floor", "Math.floor(x)")}}
+
Devuelve el mayor entero menor que o igual a un número.
+
{{jsxref("Global_Objects/Math/fround", "Math.fround(x)")}}
+
Devuelve la representación flotante de precisión simple más cercana de un número.
+
{{jsxref("Global_Objects/Math/hypot", "Math.hypot([x[, y[, …]]])")}}
+
Devuelve la raíz cuadrada de la suma de los cuadrados de sus argumentos.
+
{{jsxref("Global_Objects/Math/imul", "Math.imul(x, y)")}}
+
Devuelve el resultado de una multiplicación de enteros de 32 bits.
+
{{jsxref("Global_Objects/Math/log", "Math.log(x)")}}
+
Devuelve el logaritmo natural (log, también ln) de un número.
+
{{jsxref("Global_Objects/Math/log1p", "Math.log1p(x)")}}
+
Devuelve el logaritmo natural de x + 1 (loge, también ln) de un número.
+
{{jsxref("Global_Objects/Math/log10", "Math.log10(x)")}}
+
Devuelve el logaritmo en base 10 de x.
+
{{jsxref("Global_Objects/Math/log2", "Math.log2(x)")}}
+
Devuelve el logaritmo en base 2 de x.
+
{{jsxref("Global_Objects/Math/max", "Math.max([x[, y[, …]]])")}}
+
Devuelve el mayor de cero o más números.
+
{{jsxref("Global_Objects/Math/min", "Math.min([x[, y[, …]]])")}}
+
Devuelve el más pequeño de cero o más números.
+
{{jsxref("Global_Objects/Math/pow", "Math.pow(x, y)")}}
+
Las devoluciones de base a la potencia de exponente, que es, baseexponent.
+
{{jsxref("Global_Objects/Math/random", "Math.random()")}}
+
Devuelve un número pseudo-aleatorio entre 0 y 1.
+
{{jsxref("Global_Objects/Math/round", "Math.round(x)")}}
+
Devuelve el valor de un número redondeado al número entero más cercano.
+
{{jsxref("Global_Objects/Math/sign", "Math.sign(x)")}}
+
Devuelve el signo de la x, que indica si x es positivo, negativo o cero.
+
{{jsxref("Global_Objects/Math/sin", "Math.sin(x)")}}
+
Devuelve el seno de un número.
+
{{jsxref("Global_Objects/Math/sinh", "Math.sinh(x)")}}
+
Devuelve el seno hiperbólico de un número.
+
{{jsxref("Global_Objects/Math/sqrt", "Math.sqrt(x)")}}
+
Devuelve la raíz cuadrada positiva de un número.
+
{{jsxref("Global_Objects/Math/tan", "Math.tan(x)")}}
+
Devuelve la tangente de un número.
+
{{jsxref("Global_Objects/Math/tanh", "Math.tanh(x)")}}
+
Devuelve la tangente hiperbólica de un número.
+
+
Math.toSource() {{non-standard_inline}}
+
+
Devuelve la cadena "Math".
+
{{jsxref("Global_Objects/Math/trunc", "Math.trunc(x)")}}
+
Devuelve la parte entera del número x, la eliminación de los dígitos fraccionarios.
+
+ +

Extendiendo el objeto Math

+ +

Como muchos de los objetos incluidos en JavaScript, el objeto Math puede ser extendido con propiedades y métodos personalizados. Para extender el objeto Math no se debe usar 'prototype'. Es posible extender directamente Math:

+ +
Math.propName = propValue;
+Math.methodName = methodRef;
+ +

Como demostración, el siguiente ejemplo agrega un método al objeto Math para calcular el máximo común divisor de una lista de argumentos.

+ +
/* Función variádica -- Retorna el máximo común divisor de una lista de argumentos */
+Math.gcd = function() {
+    if (arguments.length == 2) {
+        if (arguments[1] == 0)
+            return arguments[0];
+        else
+            return Math.gcd(arguments[1], arguments[0] % arguments[1]);
+    } else if (arguments.length > 2) {
+        var result = Math.gcd(arguments[0], arguments[1]);
+        for (var i = 2; i < arguments.length; i++)
+            result = Math.gcd(result, arguments[i]);
+        return result;
+    }
+};
+ +

Pruébalo:

+ +
console.log(Math.gcd(20, 30, 15, 70, 40)); // `5`
+ +

Especificaciones

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaciónEstadoComentario
{{SpecName('ES1')}}{{Spec2('ES1')}}Definición Inicial. Implementado en JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.8', 'Math')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-math-object', 'Math')}}{{Spec2('ES6')}}Nuevos métodos {{jsxref("Math.log10()", "log10()")}}, {{jsxref("Math.log2()", "log2()")}}, {{jsxref("Math.log1p()", "log1p()")}}, {{jsxref("Math.expm1()", "expm1()")}}, {{jsxref("Math.cosh()", "cosh()")}}, {{jsxref("Math.sinh()", "sinh()")}}, {{jsxref("Math.tanh()", "tanh()")}}, {{jsxref("Math.acosh()", "acosh()")}}, {{jsxref("Math.asinh()", "asinh()")}}, {{jsxref("Math.atanh()", "atanh()")}}, {{jsxref("Math.hypot()", "hypot()")}}, {{jsxref("Math.trunc()", "trunc()")}}, {{jsxref("Math.sign()", "sign()")}}, {{jsxref("Math.imul()", "imul()")}}, {{jsxref("Math.fround()", "fround()")}}, {{jsxref("Math.cbrt()", "cbrt()")}} y {{jsxref("Math.clz32()", "clz32()")}} añadidos.
{{SpecName('ESDraft', '#sec-math-object', 'Math')}}{{Spec2('ESDraft')}}
+ +

Compatibilidad con navegadores

+ +
{{Compat("javascript.builtins.Math")}}
+ +

Ver también

+ + diff --git a/files/es/web/javascript/reference/global_objects/math/ln10/index.html b/files/es/web/javascript/reference/global_objects/math/ln10/index.html new file mode 100644 index 0000000000..8b9f40b77b --- /dev/null +++ b/files/es/web/javascript/reference/global_objects/math/ln10/index.html @@ -0,0 +1,84 @@ +--- +title: Math.LN10 +slug: Web/JavaScript/Referencia/Objetos_globales/Math/LN10 +tags: + - JavaScript + - Math + - Property + - Referencia +translation_of: Web/JavaScript/Reference/Global_Objects/Math/LN10 +--- +
{{JSRef}}
+ +

La propiedad Math.LN10 representa el logaritmo natural de 10, aproximadamente 2.302:

+ +

Math.LN10=ln(10)2.302\mathtt{\mi{Math.LN10}} = \ln(10) \approx 2.302

+ +
{{EmbedInteractiveExample("pages/js/math-ln10.html")}}
+ +
 
+ +
{{js_property_attributes(0, 0, 0)}}
+ +

Descripción

+ +

Porque LN10 es una propiedad estática de Math, siempre usted lo usa como Math.LN10, en lugar de como una propiedad de un objeto Math creado (Math no es un constructor).

+ +

Ejemplos

+ +

Utilizando Math.LN10

+ +

La función siguiente devuelve el logaritmo natural de 10:

+ +
function getNatLog10() {
+   return Math.LN10
+}
+
+getNatLog10(); // 2.302585092994046
+
+ +

Especificaciones

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaciónEstadoComentario
{{SpecName('ES1')}}{{Spec2('ES1')}}Definición inicial. Implementado en JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.8.1.2', 'Math.LN10')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math.ln10', 'Math.LN10')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-math.ln10', 'Math.LN10')}}{{Spec2('ESDraft')}} 
+ +

Compatibilidad con navegadores

+ + + +

{{Compat("javascript.builtins.Math.LN10")}}

+ +

Ver también

+ + diff --git a/files/es/web/javascript/reference/global_objects/math/ln2/index.html b/files/es/web/javascript/reference/global_objects/math/ln2/index.html new file mode 100644 index 0000000000..4a447f677a --- /dev/null +++ b/files/es/web/javascript/reference/global_objects/math/ln2/index.html @@ -0,0 +1,83 @@ +--- +title: Math.LN2 +slug: Web/JavaScript/Referencia/Objetos_globales/Math/LN2 +tags: + - JavaScript + - Math + - Property + - Referencia +translation_of: Web/JavaScript/Reference/Global_Objects/Math/LN2 +--- +
{{JSRef}}
+ +

La propiedad Math.LN2 representa el logaritmo natural de 2, aproximadamente 0.693:

+ +

Math.LN2=ln(2)0.693\mathtt{\mi{Math.LN2}} = \ln(2) \approx 0.693

+ +
{{EmbedInteractiveExample("pages/js/math-ln2.html")}}
+ +
 
+ +
{{js_property_attributes(0, 0, 0)}}
+ +

Descripción

+ +

Como LN2 es una propiedad estática de Math, siempre se usa como Math.LN2, en lugar de como una propiedad de un objeto Math que ha creado (Math no es un constructor).

+ +

Ejemplos

+ +

Utilizando Math.LN2

+ +

La función siguiente devuelve el logaritmo natural de 2:

+ +
function getNatLog2() {
+  return Math.LN2;
+}
+
+getNatLog2(); // 0.6931471805599453
+ +

Especificaciones

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaciónEstadoComentario
{{SpecName('ES1')}}{{Spec2('ES1')}}Definición inicial. Implementado en JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.8.1.3', 'Math.LN2')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math.ln2', 'Math.LN2')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-math.ln2', 'Math.LN2')}}{{Spec2('ESDraft')}} 
+ +

Compatibilidad con navegadores

+ + + +

{{Compat("javascript.builtins.Math.LN2")}}

+ +

Ver también

+ + diff --git a/files/es/web/javascript/reference/global_objects/math/log/index.html b/files/es/web/javascript/reference/global_objects/math/log/index.html new file mode 100644 index 0000000000..d243cd0501 --- /dev/null +++ b/files/es/web/javascript/reference/global_objects/math/log/index.html @@ -0,0 +1,112 @@ +--- +title: Math.log() +slug: Web/JavaScript/Referencia/Objetos_globales/Math/log +translation_of: Web/JavaScript/Reference/Global_Objects/Math/log +--- +
{{JSRef}}
+ +

La función Math.log() devuelve la base neutral de un número (base {{jsxref ("Math.E", "e")}})

+ +

x>0,Math.log(x)=ln(x)=the uniqueysuch thatey=x\forall x > 0, \mathtt{\operatorname{Math.log}(x)} = \ln(x) = \text{el unico} \; y \; \text{tal que} \; e^y = x

+ +

 

+ +

La función en JavaScrcrip Math.log() es equivalente a ln(x) en matematicas.

+ +
{{EmbedInteractiveExample("pages/js/math-log.html")}}
+ + + +

Sintaxis

+ +
Math.log(x)
+ +

Parametetros

+ +
+
x
+
Es un numero.
+
+ +

Retorna el valor

+ +

 

+ +

La base natural (base {{jsxref("Math.E", "e")}}) del número dado. Si el número es negativo, se devuelve {{jsxref("NaN")}} 

+ +

Descripcion

+ +

If the value of x is negative, the return value is always {{jsxref("NaN")}}.

+ +

Because log() is a static method of Math, you always use it as Math.log(), rather than as a method of a Math object you created (Math is not a constructor).

+ +

If you need the natural log of 2 or 10, use the constants {{jsxref("Math.LN2")}} or {{jsxref("Math.LN10")}} .  If you need a logarithm to base 2 or 10, use {{jsxref("Math.log2()")}} or {{jsxref("Math.log10()")}} .  If you need a logarithm to other bases, use Math.log(x) / Math.log(otherBase) as in the example below; you might want to precalculate 1 / Math.log(otherBase) .

+ +

Examples

+ +

Using Math.log()

+ +
Math.log(-1); // NaN, out of range
+Math.log(0);  // -Infinity
+Math.log(1);  // 0
+Math.log(10); // 2.302585092994046
+
+ +

Using Math.log() with a different base

+ +

The following function returns the logarithm of y with base x (ie. logxy\log_x y):

+ +
function getBaseLog(x, y) {
+  return Math.log(y) / Math.log(x);
+}
+
+ +

If you run getBaseLog(10, 1000) it returns 2.9999999999999996 due to floating-point rounding, which is very close to the actual answer of 3.

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.8.2.10', 'Math.log')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math.log', 'Math.log')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-math.log', 'Math.log')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ + + +

{{Compat("javascript.builtins.Math.log")}}

+ +

See also

+ + diff --git a/files/es/web/javascript/reference/global_objects/math/log10/index.html b/files/es/web/javascript/reference/global_objects/math/log10/index.html new file mode 100644 index 0000000000..dc97208b63 --- /dev/null +++ b/files/es/web/javascript/reference/global_objects/math/log10/index.html @@ -0,0 +1,137 @@ +--- +title: Math.log10() +slug: Web/JavaScript/Referencia/Objetos_globales/Math/log10 +translation_of: Web/JavaScript/Reference/Global_Objects/Math/log10 +--- +
{{JSRef}}
+ +

Math.log10() funcion que retorna el logaritmo de base 10 de un numero, esto es

+ +

x>0,Math.log10(x)=log10(x)=la unicay tal que10y=x\forall x > 0, \mathtt{\operatorname{Math.log10}(x)} = \log_10(x) = \text{the unique} \; y \; \text{such that} \; 10^y = x

+ +

Sintaxis

+ +
Math.log10(x)
+ +

Parametros

+ +
+
x
+
Un Numero
+
+ +

Valor de Retorno

+ +

El logaritmo de base 10 del numero dado. SI el numero es negativo, {{jsxref("NaN")}} es devuelto.

+ +

Descripción

+ +

Si el valor de x es menor que cero, el valor de retorno siempre es {{jsxref("NaN")}}.

+ +

Porque log10() es un metodo estatico de Math, debe usarse siempre Math.log10(), en vez de usarse como un metodo del objeto math que se ha creado (Math no es un constructor).

+ +

Esta función es equivalente de Math.log(x) / Math.log(10).  Para log10(e) use la constante {{jsxref("Math.LOG10E")}} que es 1 / {{jsxref("Math.LN10")}}.  

+ +

Ejemplos

+ +

usando Math.log10()

+ +
Math.log10(2);      // 0.3010299956639812
+Math.log10(1);      // 0
+Math.log10(0);      // -Infinito
+Math.log10(-2);     // NaN
+Math.log10(100000); // 5
+
+ +

Polyfill

+ +

Puede ser emulada con la siguiente función

+ +
Math.log10 = Math.log10 || function(x) {
+  return Math.log(x) * Math.LOG10E;
+};
+
+ +

Especificaciones

+ + + + + + + + + + + + + + + + + + + +
EspecificacionEstadoComentarios
{{SpecName('ES6', '#sec-math.log10', 'Math.log10')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-math.log10', 'Math.log10')}}{{Spec2('ESDraft')}} 
+ +

Compatibilidad con Navegadores

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
CaracteristicaChromeFirefox (Gecko)Internet ExplorerOperaSafari
Soporte Básico{{CompatChrome("38")}}{{CompatGeckoDesktop("25")}}{{CompatNo}}{{CompatOpera("25")}}{{CompatSafari("7.1")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
CaracteristicaAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Soporte Básico{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile("25")}}{{CompatNo}}{{CompatNo}}8
+
+ +

Vea Tambien

+ + diff --git a/files/es/web/javascript/reference/global_objects/math/log10e/index.html b/files/es/web/javascript/reference/global_objects/math/log10e/index.html new file mode 100644 index 0000000000..755b6ceb1a --- /dev/null +++ b/files/es/web/javascript/reference/global_objects/math/log10e/index.html @@ -0,0 +1,130 @@ +--- +title: Math.LOG10E +slug: Web/JavaScript/Referencia/Objetos_globales/Math/LOG10E +tags: + - JavaScript + - Math + - Propiedad + - Referencia +translation_of: Web/JavaScript/Reference/Global_Objects/Math/LOG10E +--- +
{{JSRef}}
+ +
 
+ +
La propiedad Math.LOG10E representa el logaritmo base 10 de e, el cual es aproximadamente 0.434:
+ +

Math.LOG10E=log10(e)0.434\mathtt{\mi{Math.LOG10E}} = \log_10(e) \approx 0.434

+ +
{{js_property_attributes(0, 0, 0)}}
+ +

Descripción

+ +

Debido a que LOG10E es una propiedad estatica del módulo Math, se debe de invocar siempre como Math.LOG10E, en lugar de invocarla como una propiedad de algun objeto Math que hayas creado ( Math no es un constructor ).

+ +

Ejemplos

+ +

Utilizando Math.LOG10E

+ +

La siguiente funcion regresa el logaritmo base 10 de e:

+ +
function getLog10e() {
+  return Math.LOG10E;
+}
+
+getLog10e(); // 0.4342944819032518
+
+ +

Especificaciones

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificacionEstatusComentarios
{{SpecName('ES1')}}{{Spec2('ES1')}} +

Definición inicial. Implementado en JavaScript 1.0.

+
{{SpecName('ES5.1', '#sec-15.8.1.5', 'Math.LOG10E')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math.log10e', 'Math.LOG10E')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-math.log10e', 'Math.LOG10E')}}{{Spec2('ESDraft')}} 
+ + + +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
CaracteristicaChromeFirefox (Gecko)Internet ExplorerOperaSafari
Soporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
CaracteristicaAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Soporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Ver tambien

+ + diff --git a/files/es/web/javascript/reference/global_objects/math/log2/index.html b/files/es/web/javascript/reference/global_objects/math/log2/index.html new file mode 100644 index 0000000000..b394270684 --- /dev/null +++ b/files/es/web/javascript/reference/global_objects/math/log2/index.html @@ -0,0 +1,96 @@ +--- +title: Math.log2() +slug: Web/JavaScript/Referencia/Objetos_globales/Math/log2 +translation_of: Web/JavaScript/Reference/Global_Objects/Math/log2 +--- +
{{JSRef}}
+ +

La función Math.log2() retorna el logaritmo base 2 de un número, esto es

+ +

x>0,Math.log2(x)=log2(x)=the uniqueysuch that2y=x\forall x > 0, \mathtt{\operatorname{Math.log2}(x)} = \log_2(x) = \text{the unique} \; y \; \text{such that} \; 2^y = x

+ +
{{EmbedInteractiveExample("pages/js/math-log2.html")}}
+ + + +

Syntax

+ +
Math.log2(x)
+ +

Parámetros

+ +
+
x
+
Un número.
+
+ +

Valor de retorno

+ +

El logaritmo base 2 del número usado como parámetro. Si el número es negativo, {{jsxref("NaN")}} será retornado.

+ +

Descripción

+ +

Si el valor de x es mejor a 0, el valor de retorno es siempre {{jsxref("NaN")}}.

+ +

Debido a que log2() es una función estática de Math, siempre debe ser usado como Math.log2(), en lugar de ser usado como un método del objeto Math (Math no es un constructor).

+ +

Esta función es equivalente a Math.log(x) / Math.log(2).  Para log2(e) use la constante {{jsxref("Math.LOG2E")}} que es 1 / {{jsxref("Math.LN2")}}.  

+ +

Ejemplos

+ +

Usando Math.log2()

+ +
Math.log2(3);    // 1.584962500721156
+Math.log2(2);    // 1
+Math.log2(1);    // 0
+Math.log2(0);    // -Infinity
+Math.log2(-2);   // NaN
+Math.log2(1024); // 10
+
+ +

Polyfill

+ +

This Polyfill emulates the Math.log2 function. Note that it returns imprecise values on some inputs (like 1 << 29), wrap into {{jsxref("Math.round()")}} if working with bit masks.

+ +
Math.log2 = Math.log2 || function(x) {
+  return Math.log(x) * Math.LOG2E;
+};
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-math.log2', 'Math.log2')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-math.log2', 'Math.log2')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ + + +

{{Compat("javascript.builtins.Math.log2")}}

+ +

See also

+ + diff --git a/files/es/web/javascript/reference/global_objects/math/log2e/index.html b/files/es/web/javascript/reference/global_objects/math/log2e/index.html new file mode 100644 index 0000000000..f9593b4bc6 --- /dev/null +++ b/files/es/web/javascript/reference/global_objects/math/log2e/index.html @@ -0,0 +1,27 @@ +--- +title: Math.LOG2E +slug: Web/JavaScript/Referencia/Objetos_globales/Math/LOG2E +tags: + - JavaScript + - Math + - Property +translation_of: Web/JavaScript/Reference/Global_Objects/Math/LOG2E +--- +
+ {{JSRef("Objetos_globales", "Math")}}
+

Resumen

+

El base 2 del logaritmo natural de E (aproximadamente 1.442).

+
+ {{js_property_attributes(0,0,0)}}
+

Descripción

+

Porque LOG2E es una propiedad estática de Math, siempre usted lo usa como Math.LOG2E, en lugar de una propedad de un objecto de Math usted creó.

+

Ejemplos

+

Ejemplo: Usar Math.LOG2E

+

La función siguiente devuelve el base 2 del logaritmo natural del E:

+
function getLog2e() {
+   return Math.LOG2E
+}
+

Ven También

+ diff --git a/files/es/web/javascript/reference/global_objects/math/max/index.html b/files/es/web/javascript/reference/global_objects/math/max/index.html new file mode 100644 index 0000000000..0e0f82881c --- /dev/null +++ b/files/es/web/javascript/reference/global_objects/math/max/index.html @@ -0,0 +1,145 @@ +--- +title: Math.max() +slug: Web/JavaScript/Referencia/Objetos_globales/Math/max +tags: + - JavaScript + - Math + - Método(2) + - Referencia +translation_of: Web/JavaScript/Reference/Global_Objects/Math/max +--- +
{{JSRef("Global_Objects", "Math")}}
+ +

Resumen

+ +

La función Math.max() devuelve el mayor de cero o más números.

+ +

Sintaxis

+ +
Math.max([valor1[, valor2[, ...]]])
+ +

Parámetros

+ +
+
valor1, valor2, ...
+
Números.
+
+ +

Descripción

+ +

Ya que max() es un método estático de Math, siempre debe usarse como Math.max(), en lugar de un método de un objeto Math instanciado (Math no es un constructor).

+ +

Si no se proporcionan argumentos, el resultado es -{{jsxref("Global_Objects/Infinity", "Infinity")}}.

+ +

Si al menos uno de los argumentos no puede ser convertido a número, el resultado es {{jsxref("Global_Objects/NaN", "NaN")}}.

+ +

Ejemplos

+ +

Ejemplo: Usando Math.max()

+ +
Math.max(10, 20);   //  20
+Math.max(-10, -20); // -10
+Math.max(-10, 20);  //  20
+
+ +

La siguiente función usa {{jsxref("Function.prototype.apply()")}} para encontrar el elemento mayor en un array numérico. getMaxOfArray([1, 2, 3]) es equivalente a Math.max(1, 2, 3), pero se puede usar getMaxOfArray() sobre arreglos construidos programáticamente de cualquier tamaño.

+ +
function getMaxOfArray(numArray) {
+  return Math.max.apply(null, numArray);
+}
+
+ +

O con el nuevo {{jsxref("Operadores/Spread_operator", "spread operator")}}, obtener el máximo de un arreglo se vuelve mucho más fácil.

+ +
var arr = [1, 2, 3];
+var max = Math.max(...arr);
+ +

Especificaciones

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaciónEstatusComentario
ECMAScript 1ra Edición.EstandarDefinición inicial. Implementado en JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.8.2.11', 'Math.max')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math.max', 'Math.max')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-math.max', 'Math.max')}}{{Spec2('ESDraft')}} 
+ +

Compatibilidad con navegadores

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari
Soporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidChrome para AndroidFirefox Móvil (Gecko)IE MóvilOpera MóvilSafari Móvil
Soporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Ver además

+ + diff --git a/files/es/web/javascript/reference/global_objects/math/min/index.html b/files/es/web/javascript/reference/global_objects/math/min/index.html new file mode 100644 index 0000000000..a2dbf8348a --- /dev/null +++ b/files/es/web/javascript/reference/global_objects/math/min/index.html @@ -0,0 +1,150 @@ +--- +title: Math.min() +slug: Web/JavaScript/Referencia/Objetos_globales/Math/min +tags: + - JavaScript + - Math + - Referencia + - metodo +translation_of: Web/JavaScript/Reference/Global_Objects/Math/min +--- +
{{JSRef}}
+ +

La función Math.min() devuelve el menor de cero o más números.

+ +

Sintaxis

+ +
Math.min([valor1[, valor2[, ...]]])
+ +

Parámetros

+ +
+
valor1, valor2, ...
+
Números.
+
+ +

Descripción

+ +

Ya que min() es un método estático de Math, siempre debe usarse como Math.min(), en lugar de como un método de un objeto Math instanciado (Math no es un constructor).

+ +

Si no se proporcionan argumentos, el resultado es {{jsxref("Infinity")}}.

+ +

Si al menos uno de los argumentos no puede ser convertido a número, el resultado es {{jsxref("NaN")}}.

+ +

Ejemplos

+ +

Usando Math.min()

+ +

Lo siguiente encuentra el mínimo de x e y y lo asigna a z:

+ +
var x = 10, y = -20;
+var z = Math.min(x, y);
+
+ +

Recortando un valor con Math.min()

+ +

Math.min() es a menudo usado para recortar un valor de tal manera que siempre sea menor o igual a un límite. Este ejemplo

+ +
var x = f(foo);
+
+if (x > limite) {
+  x = limite;
+}
+
+ +

puede ser escrito de la siguiente manera

+ +
var x = Math.min(f(foo), limite);
+
+ +

{{jsxref("Math.max()")}} puede ser usado en una forma similar para recortar un valor en el otro extremo.

+ +

Especificaciones

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaciónEstatusComentario
{{SpecName('ES1')}}{{Spec2('ES1')}}Definición inicial. Implementada en JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.8.2.12', 'Math.min')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math.min', 'Math.min')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-math.min', 'Math.min')}}{{Spec2('ESDraft')}} 
+ +

Compatibilidad con navegadores

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari
Soporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidChrome para AndroidFirefox Móvil (Gecko)IE MóvilOpera MóvilSafari Móvil
Soporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Ver además

+ + diff --git a/files/es/web/javascript/reference/global_objects/math/pi/index.html b/files/es/web/javascript/reference/global_objects/math/pi/index.html new file mode 100644 index 0000000000..d4428498cd --- /dev/null +++ b/files/es/web/javascript/reference/global_objects/math/pi/index.html @@ -0,0 +1,126 @@ +--- +title: Math.PI +slug: Web/JavaScript/Referencia/Objetos_globales/Math/PI +tags: + - JavaScript + - Math + - Propiedad + - Referencia +translation_of: Web/JavaScript/Reference/Global_Objects/Math/PI +--- +
{{JSRef}}
+ +
La propiedad Math.PI representa la relacion entre la longitud de la circunferencia de un circulo y su diametro, la cual es aproximadamente 3.14159.
+ +

Math.PI=π3.14159\mathtt{\mi{Math.PI}} = \pi \approx 3.14159

+ +
{{js_property_attributes(0, 0, 0)}}
+ +

Descripción

+ +

Debido a que PI es una propiedad estatica del modulo Math, siempre debes de utilizarla como Math.PI, en lugar de una propiedad de un objeto Math que tu hayas creado ( Math no es un constructor ).

+ +

Ejemplos

+ +

Utilizando Math.PI

+ +

La siguiente función utiliza Math.PI para calcular la longitud de la circunferencia de un circulo mediante el radio del circulo proporcionado como parametro.

+ +
function calculaCircunferencia(radio) {
+  return 2 * Math.PI * radio;
+}
+
+calculaCircunferencia(1);  // 6.283185307179586
+
+ +

Especificaciones

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaciónEstatusComentario
{{SpecName('ES1')}}{{Spec2('ES1')}} +

Definición inicial. Implementado en JavaScript 1.0.

+
{{SpecName('ES5.1', '#sec-15.8.1.6', 'Math.PI')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math.pi', 'Math.PI')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-math.pi', 'Math.PI')}}{{Spec2('ESDraft')}} 
+ + + +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
CaracteristicaChromeFirefox (Gecko)Internet ExplorerOperaSafari
Soporte Basico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
CaracteristicaAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Soporte Basico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Ver tambien

+ + diff --git a/files/es/web/javascript/reference/global_objects/math/pow/index.html b/files/es/web/javascript/reference/global_objects/math/pow/index.html new file mode 100644 index 0000000000..7185cffede --- /dev/null +++ b/files/es/web/javascript/reference/global_objects/math/pow/index.html @@ -0,0 +1,140 @@ +--- +title: Math.pow() +slug: Web/JavaScript/Referencia/Objetos_globales/Math/pow +translation_of: Web/JavaScript/Reference/Global_Objects/Math/pow +--- +
{{JSRef("Global_Objects", "Math")}}
+ +

Resumen

+ +

La función  Math.pow() devuelve la  base elevada al exponente , esto es, baseexponente.

+ +

Sintaxis

+ +
Math.pow(base, exponente)
+ +

Parametros

+ +
+
base
+
El número base.
+
exponente
+
El exponente utilizado para elevar la base.
+
+ +

Descripción

+ +

La función Math.pow() retorna la base elevada al exponente, es decir, baseexponente. La base y el exponente estan en el sistema numérico decimal.

+ +

Puesto que pow() es un método estático de Math, siempre se utiliza como Math.pow(). Si la base es negativa y el exponente no es un número entero, el resultado será NaN.

+ +

Ejemplos

+ +

Ejemplo: Usando Math.pow()

+ +
// simple
+Math.pow(7, 2);    // 49
+Math.pow(7, 3);    // 343
+Math.pow(2, 10);   // 1024
+// exponentes fraccionales
+Math.pow(4, 0.5);  // 2 (raíz cuadrada de 4)
+Math.pow(8, 1/3);  // 2 (raíz cúbica de 8)
+Math.pow(2, 0.5);  // 1.412135623730951 (raíz cuadrada de 2)
+Math.pow(2, 1/3);  // 1.2599210498948732 (raíz cúbica de 2)
+// exponentes con signo
+Math.pow(7, -2);   // 0.02040816326530612 (1/49)
+Math.pow(8, -1/3); // 0.5
+// bases con signo
+Math.pow(-7, 2);   // 49 (los cuadrados son positivos)
+Math.pow(-7, 3);   // -343 (El cubo de una base negativa puede ser negativo)
+Math.pow(-7, 0.5); // NaN (Los números negativos no tienen raíz cuadrada real)
+Math.pow(-7, 1/3); // NaN
+
+ +

Especificaciones

+ + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaciónEstadoComentarios
ECMAScript 1st Edition.EstándarDefinición inicial implementada en JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.8.2.13', 'Math.pow')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-math.pow', 'Math.pow')}}{{Spec2('ES6')}}
+ +

Compatibilidad con navegadores

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari
Soporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidChrome para AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Soporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Ver también

+ + diff --git a/files/es/web/javascript/reference/global_objects/math/random/index.html b/files/es/web/javascript/reference/global_objects/math/random/index.html new file mode 100644 index 0000000000..ace95bc0cf --- /dev/null +++ b/files/es/web/javascript/reference/global_objects/math/random/index.html @@ -0,0 +1,132 @@ +--- +title: Math.random() +slug: Web/JavaScript/Referencia/Objetos_globales/Math/random +tags: + - JavaScript + - Math + - Números Aleatorios + - Random + - Referências +translation_of: Web/JavaScript/Reference/Global_Objects/Math/random +--- +
{{JSRef("Global_Objects", "Math")}}
+ +

Sumario

+ +

La función Math.random() retorna un punto flotante, un número pseudo-aleatorio dentro del rango [0, 1). Esto es, desde el 0 (Incluido) hasta el 1 pero sin incluirlo (excluido), el cual se puede escalar hasta el rango deseado. La implementación selecciona la semilla inicial hasta el algoritmo que genera el número aleatorio; este no puede ser elegido o cambiado por el usuario.

+ +
+

Nota: Math.random() NO provee números aleatorios con seguridad criptográfica. No deben ser usados para algo relacionado con seguridad. En vez de eso, usar la API Web Crypto, y más precisamente el método: {{domxref("RandomSource.getRandomValues()", "window.crypto.getRandomValues()")}}.

+
+ +

Sintaxis

+ +
Math.random()
+ +

Parámetros

+ +

Ninguno.

+ +

Ejemplos

+ +

Ejemplo: Usando Math.random()

+ +

Notar que, como los números en Javascript son números de punto flotante IEEE 754 con redondeo-al-par-más-cercano, los rangos generados por las funciones de abajo (excluyendo a Math.random() en sí misma) no son exactos. Si se eligen límites extremadamente grandes (253 o más), es posible, en casos extremadamente raros, calcular el generalmente-excluído límite superior.

+ +
// Retorna un número aleatorio entre 0 (incluido) y 1 (excluido)
+function getRandom() {
+  return Math.random();
+}
+
+ +
// Retorna un número aleatorio entre min (incluido) y max (excluido)
+function getRandomArbitrary(min, max) {
+  return Math.random() * (max - min) + min;
+}
+
+ +
// Retorna un entero aleatorio entre min (incluido) y max (excluido)
+// ¡Usando Math.round() te dará una distribución no-uniforme!
+function getRandomInt(min, max) {
+  return Math.floor(Math.random() * (max - min)) + min;
+}
+
+ +

Especificaciones

+ + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaciónEstadoComentario
ECMAScript 1a Edición.{{Spec2('ES1')}}Definición inicial. JavaScript 1.0 (Sólo UNIX) / JavaScript 1.1 (Todas las plataformas).
{{SpecName('ES5.1', '#sec-15.8.2.14', 'Math.random')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math.random', 'Math.random')}}{{Spec2('ES6')}} 
+ +

Compatibilidad en navegadores

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari
Soporte Básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Soporte Básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
diff --git a/files/es/web/javascript/reference/global_objects/math/round/index.html b/files/es/web/javascript/reference/global_objects/math/round/index.html new file mode 100644 index 0000000000..0257148e69 --- /dev/null +++ b/files/es/web/javascript/reference/global_objects/math/round/index.html @@ -0,0 +1,218 @@ +--- +title: Math.round() +slug: Web/JavaScript/Referencia/Objetos_globales/Math/round +translation_of: Web/JavaScript/Reference/Global_Objects/Math/round +--- +
{{JSRef}}
+ +
La función Math.round() retorna el valor de un número redondeado al entero más cercano.
+ +

Sumario

+ +

Devuelve el valor del número dado redondeado al entero más cercano.

+ +

Sintaxis

+ +
Math.round(x)
+ +

Parámetros

+ +
+
Un número.
+
+ +

Valor de Retorno

+ +
+
El valor del número dado redondeado al entero más cercano.
+
+ +

Descripción

+ +

Si la porción fraccionaría del número es 0.5 o mayor, el argumento es redondeado al siguiente número entero superior. Si la porción de la fracción del número es menor a 0.5, el argumento es redondeado al siguiente número entero inferior.

+ +

Debido a que round() es un método estático de Math, siempre se debe utilizar como  Math.round(),  en vez de un método del objeto Math que ha creado. (Math no es un constructor)

+ +

Ejemplos

+ +

Usando Math.round()

+ +
// Retorna el valor 20
+x = Math.round(20.49);
+
+// Retorna el valor 21
+x = Math.round(20.5);
+
+// Retorna el valor -20
+x = Math.round(-20.5);
+
+// Retorna el valor -21
+x = Math.round(-20.51);
+
+// Retorna el valor 1 (!)
+// Note el error de redondeo debido a la inexactitud del punto aritmético.
+// Compare esto con Math.round10(1.005, -2) de el ejemplo de abajo.
+x = Math.round(1.005*100)/100;
+
+ +

Redondeo decimal

+ +
// Conclusión
+(function() {
+  /**
+   * Ajuste decimal de un número.
+   *
+   * @param {String}  tipo  El tipo de ajuste.
+   * @param {Number}  valor El numero.
+   * @param {Integer} exp   El exponente (el logaritmo 10 del ajuste base).
+   * @returns {Number} El valor ajustado.
+   */
+  function decimalAdjust(type, value, exp) {
+    // Si el exp no está definido o es cero...
+    if (typeof exp === 'undefined' || +exp === 0) {
+      return Math[type](value);
+    }
+    value = +value;
+    exp = +exp;
+    // Si el valor no es un número o el exp no es un entero...
+    if (isNaN(value) || !(typeof exp === 'number' && exp % 1 === 0)) {
+      return NaN;
+    }
+    // Shift
+    value = value.toString().split('e');
+    value = Math[type](+(value[0] + 'e' + (value[1] ? (+value[1] - exp) : -exp)));
+    // Shift back
+    value = value.toString().split('e');
+    return +(value[0] + 'e' + (value[1] ? (+value[1] + exp) : exp));
+  }
+
+  // Decimal round
+  if (!Math.round10) {
+    Math.round10 = function(value, exp) {
+      return decimalAdjust('round', value, exp);
+    };
+  }
+  // Decimal floor
+  if (!Math.floor10) {
+    Math.floor10 = function(value, exp) {
+      return decimalAdjust('floor', value, exp);
+    };
+  }
+  // Decimal ceil
+  if (!Math.ceil10) {
+    Math.ceil10 = function(value, exp) {
+      return decimalAdjust('ceil', value, exp);
+    };
+  }
+})();
+
+// Round
+Math.round10(55.55, -1);   // 55.6
+Math.round10(55.549, -1);  // 55.5
+Math.round10(55, 1);       // 60
+Math.round10(54.9, 1);     // 50
+Math.round10(-55.55, -1);  // -55.5
+Math.round10(-55.551, -1); // -55.6
+Math.round10(-55, 1);      // -50
+Math.round10(-55.1, 1);    // -60
+Math.round10(1.005, -2);   // 1.01 -- compare this with Math.round(1.005*100)/100 above
+// Floor
+Math.floor10(55.59, -1);   // 55.5
+Math.floor10(59, 1);       // 50
+Math.floor10(-55.51, -1);  // -55.6
+Math.floor10(-51, 1);      // -60
+// Ceil
+Math.ceil10(55.51, -1);    // 55.6
+Math.ceil10(51, 1);        // 60
+Math.ceil10(-55.59, -1);   // -55.5
+Math.ceil10(-59, 1);       // -50
+
+ +

Especificaciones

+ + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaciónEstadoComentario
{{SpecName('ES1')}}{{Spec2('ES1')}} +

Definición inicial. Implementada en JavaScript 1.0.

+
{{SpecName('ES5.1', '#sec-15.8.2.15', 'Math.round')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-math.round', 'Math.round')}}{{Spec2('ES6')}}
+ +

Compatibilidad en navegadores

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Soporte Básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Soporte Básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Véase también

+ + diff --git a/files/es/web/javascript/reference/global_objects/math/sign/index.html b/files/es/web/javascript/reference/global_objects/math/sign/index.html new file mode 100644 index 0000000000..3c48027556 --- /dev/null +++ b/files/es/web/javascript/reference/global_objects/math/sign/index.html @@ -0,0 +1,151 @@ +--- +title: Math.sign() +slug: Web/JavaScript/Referencia/Objetos_globales/Math/sign +tags: + - JavaScript + - Math + - Method + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Math/sign +--- +
{{JSRef}}
+ +

La función Math.sign() retorna el signo de un número, indicando si el número es positivo, negativo o cero.

+ +

Syntaxis

+ +
Math.sign(x)
+ +

Parametros

+ +
+
x
+
Un número.
+
+ +

Valor de retorno.

+ +

Un número representando el signo del argumento dado. Si el argumento es un número positivo, negativo, cero positivo, o cero negativo, la función retornará 1, -1, 0 or -0 respectivamente. De lo contrario, retorna {{jsxref("NaN")}}.

+ +

Descripción

+ +

Como sign() es un método estático de Math, siempre se utiliza como Math.sign(), en vez de un método de un objeto Math que hayas creado. (Math no es un constructor).

+ +

Esta función tiene 5 tipos de valores de retorno, 1, -1, 0, -0, NaN, que representan "número positivo", "número negativo", "cero positivo", "cero negativo" y {{jsxref("NaN")}} respectivamente.

+ +

El argumento pasado a esta función será convertido a tipo x implicitamente.

+ +

Ejemplos

+ +

Usando Math.sign()

+ +
Math.sign(3);     //  1
+Math.sign(-3);    // -1
+Math.sign('-3');  // -1
+Math.sign(0);     //  0
+Math.sign(-0);    // -0
+Math.sign(NaN);   // NaN
+Math.sign('foo'); // NaN
+Math.sign();      // NaN
+
+ +

Polyfill

+ +
if (!Math.sign) {
+  Math.sign = function(x) {
+    // Si x es NaN, el resultado es NaN.
+    // Si x es -0, el resultado es -0.
+    // Si x es +0, el resultado es +0.
+    // Si x es negativo y no -0, el resultado es -1.
+    // Si x es positivo y no +0, el resultado es +1.
+    x = +x; // convertir a número
+    if (x === 0 || isNaN(x)) {
+      return Number(x);
+    }
+    return x > 0 ? 1 : -1;
+  };
+}
+ +

Especificaciones

+ + + + + + + + + + + + + + + + + + + +
EspecificaciónEstadoComentario
{{SpecName('ES6', '#sec-math.sign', 'Math.sign')}}{{Spec2('ES6')}}Definición inicial.
{{SpecName('ESDraft', '#sec-math.sign', 'Math.sign')}}{{Spec2('ESDraft')}} 
+ +

Compatibilidad con navegadores

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
PropiedadChromeFirefox (Gecko)Internet ExplorerOperaSafari
Soporte básico{{CompatChrome("38")}}{{CompatGeckoDesktop("25")}}{{CompatNo}}{{CompatOpera("25")}}{{CompatSafari("9")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
PropiedadAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Soporte básico{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile("25")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

Ver También

+ + diff --git a/files/es/web/javascript/reference/global_objects/math/sin/index.html b/files/es/web/javascript/reference/global_objects/math/sin/index.html new file mode 100644 index 0000000000..a89a6e635e --- /dev/null +++ b/files/es/web/javascript/reference/global_objects/math/sin/index.html @@ -0,0 +1,126 @@ +--- +title: Math.sin() +slug: Web/JavaScript/Referencia/Objetos_globales/Math/seno +translation_of: Web/JavaScript/Reference/Global_Objects/Math/sin +--- +
{{JSRef("Global_Objects", "Math")}}
+ +

Resumen

+ +

La función Math.sin() devuelve el seno de un número.

+ +

Sintaxis

+ +
Math.sin(x)
+ +

Parámetros

+ +
+
x
+
Un número (en radianes).
+
+ +

Descripción

+ +

El método Math.sin() devuelve  un valor numérico entre -1 y 1, que representa el seno del ángulo dado en radianes.
+ Debido a que sin() es un método estático de Math, siempre se usa como Math.sin(), en vez de  crear un objeto Math y usarlo como un método (Math no es un constructor).

+ +

Ejemplos

+ +

Ejemplo: Usando Math.sin()

+ +
Math.sin(0);           // 0
+Math.sin(1);           // 0.8414709848078965
+
+Math.sin(Math.PI / 2); // 1
+
+ +

Especificaciones

+ + + + + + + + + + + + + + + + + + + + + + + + +
EspecificacionesEstatusComentarios
ECMAScript 1ª Edición.{{Spec2('ES1')}}Definición inicial. Implementado en JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.8.2.16', 'Math.sin')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math.sin', 'Math.sin')}}{{Spec2('ES6')}} 
+ +

Compatibilidad con navegadores

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari
Soporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidChrome para AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Soporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Ver también

+ + diff --git a/files/es/web/javascript/reference/global_objects/math/sqrt/index.html b/files/es/web/javascript/reference/global_objects/math/sqrt/index.html new file mode 100644 index 0000000000..a3977c6f08 --- /dev/null +++ b/files/es/web/javascript/reference/global_objects/math/sqrt/index.html @@ -0,0 +1,134 @@ +--- +title: Math.sqrt() +slug: Web/JavaScript/Referencia/Objetos_globales/Math/sqrt +translation_of: Web/JavaScript/Reference/Global_Objects/Math/sqrt +--- +
{{JSRef}}
+ +

La  función Math.sqrt() retorna la raíz cuadrada de un número, que esx0,Math.sqrt(x)=x=the uniquey0such thaty2=x\forall x \geq 0, \mathtt{Math.sqrt(x)} = \sqrt{x} = \text{the unique} \; y \geq 0 \; \text{such that} \; y^2 = x

+ +

Sintaxis

+ +
Math.sqrt(x)
+ +

Parámetros

+ +
+
x
+
Un numero
+
+ +

Valor de Retorno

+ +

La raíz cuadrada del número proporcionado. Si los números son negativos, {{jsxref("NaN")}} es devuelto.

+ +

Descripción

+ +

Si el valor de x es negativo Math.sqrt() retorna {{jsxref("NaN")}}.

+ +

Debido a que sqrt() es un método estático de Math, siempre úsalo como Math.sqrt(), en lugar de un método del objeto Math que hayas creado (Math no es un constructor).

+ +

Ejemplos

+ +

Usando Math.sqrt()

+ +
Math.sqrt(9); // 3
+Math.sqrt(2); // 1.414213562373095
+
+Math.sqrt(1);  // 1
+Math.sqrt(0);  // 0
+Math.sqrt(-1); // NaN
+
+ +

Especificaciones

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaciónEstadoComentario
{{SpecName('ES1')}}{{Spec2('ES1')}}Definición inicial. Implementada en JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.8.2.17', 'Math.sqrt')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math.sqrt', 'Math.sqrt')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-math.sqrt', 'Math.sqrt')}}{{Spec2('ESDraft')}} 
+ +

Compatibilidad

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari
Soporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Soporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Ver también

+ + diff --git a/files/es/web/javascript/reference/global_objects/math/sqrt1_2/index.html b/files/es/web/javascript/reference/global_objects/math/sqrt1_2/index.html new file mode 100644 index 0000000000..de9bd99eb9 --- /dev/null +++ b/files/es/web/javascript/reference/global_objects/math/sqrt1_2/index.html @@ -0,0 +1,123 @@ +--- +title: Math.SQRT1_2 +slug: Web/JavaScript/Referencia/Objetos_globales/Math/SQRT1_2 +tags: + - JavaScript + - Math + - Propiedad + - Referencia +translation_of: Web/JavaScript/Reference/Global_Objects/Math/SQRT1_2 +--- +
{{JSRef}}
+ +
La propiedad Math.SQRT1_2 representa la raiz cuadrada de 1/2, la cual es equivalente al inverso de la raiz cuadrada de 2, aproximadadamente 0.707:
+ +

Math.SQRT1_2=12=120.707\mathtt{\mi{Math.SQRT1_2}} = \sqrt{\frac{1}{2}} = \frac{1}{\sqrt{2}} \approx 0.707

+ +

Descripción

+ +

Debido a que SQRT1_2 es una propiedad estatica de Math, siempre debes utilizarla como Math.SQRT1_2, en lugar de invocarla como una propiedad de alguna instancia de Math que hayas creado ( Math no es un constructor ).

+ +

Ejemplos

+ +

Utilizando Math.SQRT1_2

+ +

La siguiente funcion regresa la raiz cuadrada de 1/2:

+ +
function getRoot1_2() {
+  return Math.SQRT1_2;
+}
+
+getRoot1_2(); // 0.7071067811865476
+
+ +

Especificaciones

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaciónEstatusComentarios
{{SpecName('ES1')}}{{Spec2('ES1')}}Definición inicial. Implementado en Javascript 1.0.
{{SpecName('ES5.1', '#sec-15.8.1.7', 'Math.SQRT1_2')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math.sqrt1_2', 'Math.SQRT1_2')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-math.sqrt1_2', 'Math.SQRT1_2')}}{{Spec2('ESDraft')}} 
+ + + +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
CaracteristicaChromeFirefox (Gecko)Internet ExplorerOperaSafari
Soporte basico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
CaracteristicaAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Soporte basico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Ver Tambien

+ + diff --git a/files/es/web/javascript/reference/global_objects/math/sqrt2/index.html b/files/es/web/javascript/reference/global_objects/math/sqrt2/index.html new file mode 100644 index 0000000000..7e23295f25 --- /dev/null +++ b/files/es/web/javascript/reference/global_objects/math/sqrt2/index.html @@ -0,0 +1,124 @@ +--- +title: Math.SQRT2 +slug: Web/JavaScript/Referencia/Objetos_globales/Math/SQRT2 +translation_of: Web/JavaScript/Reference/Global_Objects/Math/SQRT2 +--- +
{{JSRef}}
+ +
La propiedad Math.SQRT2 representa la raíz cuadrada de de 2, aproximadamente 1.414:
+ +

Math.SQRT2=21.414\mathtt{\mi{Math.SQRT2}} = \sqrt{2} \approx 1.414

+ +
{{js_property_attributes(0, 0, 0)}}
+ +

Descripción

+ +

Debido a que SQRT2 es una propiedad estática de Math, siempre se utiliza como Math.SQRT2, en lugar de una propiedad de un objeto Math creado.

+ +

Ejemplos

+ +

Utilizando Math.SQRT2

+ +

La siguiente función retorna la raíz cuadrada de 2:

+ +
function getRoot2() {
+  return Math.SQRT2;
+}
+
+getRoot2(); // 1.4142135623730951
+
+ +

Especificaciones

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaciónEstadoComentarios
{{SpecName('ES1')}}{{Spec2('ES1')}} +

Definición inicial. Implementada en JavaScript 1.0.

+
{{SpecName('ES5.1', '#sec-15.8.1.8', 'Math.SQRT2')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math.sqrt2', 'Math.SQRT2')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-math.sqrt2', 'Math.SQRT2')}}{{Spec2('ESDraft')}} 
+ +

Compatibilidad en navegadores

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari
Soporte Básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Soporte Básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

 

+ +

Ver también

+ + diff --git a/files/es/web/javascript/reference/global_objects/math/tan/index.html b/files/es/web/javascript/reference/global_objects/math/tan/index.html new file mode 100644 index 0000000000..8a773b0da5 --- /dev/null +++ b/files/es/web/javascript/reference/global_objects/math/tan/index.html @@ -0,0 +1,82 @@ +--- +title: Math.tan() +slug: Web/JavaScript/Referencia/Objetos_globales/Math/tan +tags: + - Matemáticas + - Referencia + - metodo +translation_of: Web/JavaScript/Reference/Global_Objects/Math/tan +--- +
{{JSRef}}
+ +

La función Math.tan() retorna la tangente de un número.

+ +
{{EmbedInteractiveExample("pages/js/math-tan.html")}}
+ + + +

Sintaxis

+ +
Math.tan(x)
+ +

Parámetros

+ +
+
x
+
Un número que representa un ángulo en radianes.
+
+ +

Valor de retorno

+ +

La tangente del número proporcionado.

+ +

Descripción

+ +

El método Math.tan() retorna un valor numérico que representa la tangente de un ángulo.

+ +

Dado que tan() es un método estático de Math, siempre debes usarlo como Math.tan(), y no como un método de un objeto Math que hayas creado (Math no es un constructor).

+ +

Ejemplos

+ +

Usando Math.tan()

+ +
Math.tan(1); // 1.5574077246549023
+
+ +

Ya que la función Math.tan() acepta radianes, pero es más fácil trabajar con grados, la siguiente función acepta un valor en grados, lo convierte a radianes, y retorna la tangente de dicho valor.

+ +
function getTanDeg(deg) {
+  var rad = deg * Math.PI/180;
+  return Math.tan(rad);
+}
+
+ +

Especificaciones

+ + + + + + + + + + +
Especificación
{{SpecName('ESDraft', '#sec-math.tan', 'Math.tan')}}
+ +

Compatibilidad con el navegador

+ + + +

{{Compat("javascript.builtins.Math.tan")}}

+ +

Ver también

+ + diff --git a/files/es/web/javascript/reference/global_objects/math/tanh/index.html b/files/es/web/javascript/reference/global_objects/math/tanh/index.html new file mode 100644 index 0000000000..138c466b37 --- /dev/null +++ b/files/es/web/javascript/reference/global_objects/math/tanh/index.html @@ -0,0 +1,95 @@ +--- +title: Math.tanh() +slug: Web/JavaScript/Referencia/Objetos_globales/Math/tanh +tags: + - ECMAScript 2015 + - JavaScript + - Referencia + - metodo +translation_of: Web/JavaScript/Reference/Global_Objects/Math/tanh +--- +
{{JSRef}}
+ +

La funcion Math.tanh() devuelve la hyperbolica tangente de un numero, esto es 

+ +

tanhx=sinhxcoshx=ex-e-xex+e-x=e2x-1e2x+1\tanh x = \frac{\sinh x}{\cosh x} = \frac {e^x - e^{-x}} {e^x + e^{-x}} = \frac{e^{2x} - 1}{e^{2x}+1}

+ +
{{EmbedInteractiveExample("pages/js/math-tanh.html")}}
+ +

Sintaxis

+ +
Math.tanh(x)
+ +

Parametros

+ +
+
x
+
Un numero.
+
+ +

Devolver valor

+ +

La hyperbolica tangente del numero obtenido.

+ +

Descripcion

+ +

Porque tanh() es un metodo estatico de Math, siempre se usa como Math.tanh(), en lugar de ser un metodo de Math objeto que creas (Math no es un constructor).

+ +

Ejemplos

+ +

Usando Math.tanh()

+ +
Math.tanh(0);        // 0
+Math.tanh(Infinity); // 1
+Math.tanh(1);        // 0.7615941559557649
+
+ +

Polyfill

+ +

Esto puede ser emulado con ayuda de {{jsxref("Math.exp()")}} funcion:

+ +
Math.tanh = Math.tanh || function(x){
+    var a = Math.exp(+x), b = Math.exp(-x);
+    return a == Infinity ? 1 : b == Infinity ? -1 : (a - b) / (a + b);
+}
+
+ +

Especificaciones

+ + + + + + + + + + + + + + + + + + + +
EspecificacionEstadoComentario
{{SpecName('ES2015', '#sec-math.tanh', 'Math.tanh')}}{{Spec2('ES2015')}} +

Definicion inicial.

+
{{SpecName('ESDraft', '#sec-math.tanh', 'Math.tanh')}}{{Spec2('ESDraft')}} 
+ +

Compatibilidad con navegadores

+ + + +

{{Compat("javascript.builtins.Math.tanh")}}

+ +

 

+ + diff --git a/files/es/web/javascript/reference/global_objects/math/trunc/index.html b/files/es/web/javascript/reference/global_objects/math/trunc/index.html new file mode 100644 index 0000000000..9efe511927 --- /dev/null +++ b/files/es/web/javascript/reference/global_objects/math/trunc/index.html @@ -0,0 +1,144 @@ +--- +title: Math.trunc() +slug: Web/JavaScript/Referencia/Objetos_globales/Math/trunc +tags: + - ECMAScript6 + - JavaScript + - Math + - Método(2) + - Referencia +translation_of: Web/JavaScript/Reference/Global_Objects/Math/trunc +--- +
{{JSRef}}
+ +

La función Math.trunc() devuelve la parte entera de un numero removiendo cualquier dígito decimal (dígitos situados después de la coma).

+ +

Sintaxis.

+ +
Math.trunc(x)
+ +

Parámetros.

+ +
+
x
+
Un número.
+
+ +

Valor de retorno.

+ +

La parte entera del número dado.

+ +

Descripción.

+ +

A diferencia de los otros tres métodos de Math: {{jsxref("Math.floor()")}}, {{jsxref("Math.ceil()")}} y {{jsxref("Math.round()")}}, la forma en que Math.trunc() funciona es muy simple.  trunca (corta) el punto y los dígitos a la derecha de él, sin importar si el argumento es un número positivo o negativo.

+ +

Si el argumento es un número positivo, Math.trunc() es equivalente a Math.floor(); de otra forma Math.trunc() es equivalente a Math.ceil().

+ +

El argumento pasado a este método será convertido a un tipo numérico entero.

+ +

Debido a que trunc() es un método estático de Math, siempre úsalo como Math.trunc(), en lugar de como un método de un objeto Math que hayas creado (Math no es un constructor).

+ +

Ejemplos.

+ +

Usando Math.trunc()

+ +
Math.trunc(13.37);    // 13
+Math.trunc(42.84);    // 42
+Math.trunc(0.123);    //  0
+Math.trunc(-0.123);   // -0
+Math.trunc('-1.123'); // -1
+Math.trunc(NaN);      // NaN
+Math.trunc('foo');    // NaN
+Math.trunc();         // NaN
+
+ +

Polyfill.

+ +
Math.trunc = Math.trunc || function (x) {
+    return (x < 0 ? Math.ceil(x) : Math.floor(x));
+}
+
+ +

Especificaciones.

+ + + + + + + + + + + + + + + + + + + +
EspecificaciónEstadoComentario
{{SpecName('ES6', '#sec-math.trunc', 'Math.trunc')}}{{Spec2('ES6')}}Definición inicial.
{{SpecName('ESDraft', '#sec-math.trunc', 'Math.trunc')}}{{Spec2('ESDraft')}}
+ +

Compatibilidad con navegadores.

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari
Soporte básico{{CompatChrome("38")}}{{CompatGeckoDesktop("25")}}{{CompatNo}}{{CompatOpera("25")}}{{CompatSafari("7.1")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Soporte Básico{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile("25")}}{{CompatNo}}{{CompatNo}}8
+
+ +

Vea también.

+ + -- cgit v1.2.3-54-g00ecf