From 074785cea106179cb3305637055ab0a009ca74f2 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:42:52 -0500 Subject: initial commit --- .../reference/global_objects/math/abs/index.html | 142 +++++++++++++ .../reference/global_objects/math/acos/index.html | 139 ++++++++++++ .../reference/global_objects/math/acosh/index.html | 100 +++++++++ .../reference/global_objects/math/asin/index.html | 103 +++++++++ .../reference/global_objects/math/asinh/index.html | 97 +++++++++ .../reference/global_objects/math/atan/index.html | 104 +++++++++ .../reference/global_objects/math/atan2/index.html | 150 +++++++++++++ .../reference/global_objects/math/atanh/index.html | 99 +++++++++ .../reference/global_objects/math/cbrt/index.html | 97 +++++++++ .../reference/global_objects/math/ceil/index.html | 210 ++++++++++++++++++ .../reference/global_objects/math/clz32/index.html | 179 ++++++++++++++++ .../reference/global_objects/math/cos/index.html | 102 +++++++++ .../reference/global_objects/math/cosh/index.html | 88 ++++++++ .../reference/global_objects/math/e/index.html | 86 ++++++++ .../reference/global_objects/math/exp/index.html | 109 ++++++++++ .../reference/global_objects/math/expm1/index.html | 80 +++++++ .../reference/global_objects/math/floor/index.html | 199 ++++++++++++++++++ .../reference/global_objects/math/hypot/index.html | 115 ++++++++++ .../reference/global_objects/math/index.html | 208 ++++++++++++++++++ .../reference/global_objects/math/ln10/index.html | 121 +++++++++++ .../reference/global_objects/math/ln2/index.html | 80 +++++++ .../reference/global_objects/math/log/index.html | 148 +++++++++++++ .../reference/global_objects/math/log10/index.html | 137 ++++++++++++ .../global_objects/math/log10e/index.html | 82 ++++++++ .../reference/global_objects/math/log1p/index.html | 105 +++++++++ .../reference/global_objects/math/log2/index.html | 91 ++++++++ .../reference/global_objects/math/log2e/index.html | 82 ++++++++ .../reference/global_objects/math/max/index.html | 155 ++++++++++++++ .../reference/global_objects/math/min/index.html | 147 +++++++++++++ .../reference/global_objects/math/pi/index.html | 82 ++++++++ .../reference/global_objects/math/pow/index.html | 147 +++++++++++++ .../global_objects/math/random/index.html | 102 +++++++++ .../reference/global_objects/math/round/index.html | 234 +++++++++++++++++++++ .../reference/global_objects/math/sign/index.html | 117 +++++++++++ .../reference/global_objects/math/sin/index.html | 92 ++++++++ .../reference/global_objects/math/sinh/index.html | 96 +++++++++ .../reference/global_objects/math/sqrt/index.html | 87 ++++++++ .../global_objects/math/sqrt1_2/index.html | 81 +++++++ .../reference/global_objects/math/sqrt2/index.html | 81 +++++++ .../reference/global_objects/math/tan/index.html | 111 ++++++++++ .../reference/global_objects/math/tanh/index.html | 88 ++++++++ .../reference/global_objects/math/trunc/index.html | 144 +++++++++++++ 42 files changed, 5017 insertions(+) create mode 100644 files/pt-br/web/javascript/reference/global_objects/math/abs/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/math/acos/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/math/acosh/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/math/asin/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/math/asinh/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/math/atan/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/math/atan2/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/math/atanh/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/math/cbrt/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/math/ceil/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/math/clz32/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/math/cos/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/math/cosh/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/math/e/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/math/exp/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/math/expm1/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/math/floor/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/math/hypot/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/math/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/math/ln10/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/math/ln2/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/math/log/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/math/log10/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/math/log10e/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/math/log1p/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/math/log2/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/math/log2e/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/math/max/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/math/min/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/math/pi/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/math/pow/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/math/random/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/math/round/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/math/sign/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/math/sin/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/math/sinh/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/math/sqrt/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/math/sqrt1_2/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/math/sqrt2/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/math/tan/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/math/tanh/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/math/trunc/index.html (limited to 'files/pt-br/web/javascript/reference/global_objects/math') diff --git a/files/pt-br/web/javascript/reference/global_objects/math/abs/index.html b/files/pt-br/web/javascript/reference/global_objects/math/abs/index.html new file mode 100644 index 0000000000..1a3658a719 --- /dev/null +++ b/files/pt-br/web/javascript/reference/global_objects/math/abs/index.html @@ -0,0 +1,142 @@ +--- +title: Math.abs() +slug: Web/JavaScript/Reference/Global_Objects/Math/abs +translation_of: Web/JavaScript/Reference/Global_Objects/Math/abs +--- +
{{JSRef("Global_Objects", "Math")}}
+ +

Sumário

+ +

A função Math.abs(x) retorna o valor absoluto de um número "x", tal qual:

+ +

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}

+ +

Sintaxe

+ +
var abs = Math.abs(x);
+ +

Parâmetros

+ +
+
x
+
Um número.
+
+ +

Valor de Retorno

+ +

O valor absoluto do número passado

+ +

Descrição.

+ +

Por abs ser um método estático de Math, você sempre o usará como Math.abs() ao ínves de usar como método de um objeto Math criado por você. (Math não é um construtor);

+ +

Exemplos

+ +

Comportamento de Math.abs()

+ +

Passando um string não-numérica ou variável indefinida/vazia retorna NaN. Passando 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
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in 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')}} 
+ +

Compatibilidade de Navegadores

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Veja Também

+ + diff --git a/files/pt-br/web/javascript/reference/global_objects/math/acos/index.html b/files/pt-br/web/javascript/reference/global_objects/math/acos/index.html new file mode 100644 index 0000000000..beea711e08 --- /dev/null +++ b/files/pt-br/web/javascript/reference/global_objects/math/acos/index.html @@ -0,0 +1,139 @@ +--- +title: Math.acos() +slug: Web/JavaScript/Reference/Global_Objects/Math/acos +translation_of: Web/JavaScript/Reference/Global_Objects/Math/acos +--- +
{{JSRef}}
+ +

A função Math.acos() retorna o arco cosseno (em radianos de um numero, sendo esse

+ +

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{ O unico } \; y \in [0; \pi] \, \text{such that} \; \cos(y) = x

+ +

Syntax

+ +
Math.acos(x)
+ +

Parâmetros 

+ +
+
Um numero.
+
+ +

Retorno

+ +

O arco cosseno(em radianos) se o valor passado como parâmetro for entre -1 e 1; caso contrario retornará {{jsxref("NaN")}}.

+ +

Description

+ +

Math.acos() metodo retorna um numero entre 0 e π radians para valores passado como parâmetros entre -1 e 1. Se o valor estiver fora dessa variação será returnado {{jsxref("NaN")}}.

+ +

Porque acos() é um metodo estático, você sempre usará Math.acos() ao invés de criar um Objecto Math(Math não é um construtor).

+ +

Examplos

+ +

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 ou maiores que than 1, Math.acos() o método retornrá {{jsxref("NaN")}}.

+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in 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')}} 
+ +

Compatibilidade entre navegadores

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

Veja também

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

A função Math.acosh() retorna o arco cosseno hiperbólico de um número, onde

+ +

x1,Math.acosh(x)=arcosh(x)= the unique y0such thatcosh(y)=x\forall x \geq 1, \mathtt{\operatorname{Math.acosh}(x)} = \operatorname{arcosh}(x) = \text{ the unique } \; y \geq 0 \; \text{such that} \; \cosh(y) = x

+ +

Sintaxe

+ +
Math.acosh(x)
+ +

Parâmetros

+ +
+
x
+
Um número.
+
+ +

Valor retornado

+ +

The hyperbolic arc-cosine of the given number. If the number is less than 1, {{jsxref("NaN")}}.

+ +

O arco cosseno hiperbólico do número recebido. Se o número for menor que 1, {{jsxref("NaN")}} é retornado.

+ +

Descrição

+ +

Por acosh() ser um método estático de Math, deve-se sempre usá-lo como Math.acosh(), e não como um método de um objeto Math que você criou.

+ +

Exemplos

+ +

Usando Math.acosh()

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

For values less than 1 Math.acosh() returns {{jsxref("NaN")}}.

+ +

Para valores menores que 1, Math.acosh() retornará {{jsxref("NaN")}}.

+ +

Polyfill

+ +

Para todo x1x \geq 1, temos arcosh(x)=ln(x+x2-1)\operatorname {arcosh} (x) = \ln \left(x + \sqrt{x^{2} - 1} \right). Dessa maneira, este comportamento pode ser emulado da seguinte maneira:

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

Especificações

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES6', '#sec-math.acosh', 'Math.acosh')}}{{Spec2('ES6')}}Definição inicial.
{{SpecName('ESDraft', '#sec-math.acosh', 'Math.acosh')}}{{Spec2('ESDraft')}} 
+ +

Compatibilidade nos navegadores

+ + + +

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

+ +

See also

+ + diff --git a/files/pt-br/web/javascript/reference/global_objects/math/asin/index.html b/files/pt-br/web/javascript/reference/global_objects/math/asin/index.html new file mode 100644 index 0000000000..7738c1e819 --- /dev/null +++ b/files/pt-br/web/javascript/reference/global_objects/math/asin/index.html @@ -0,0 +1,103 @@ +--- +title: Math.asin() +slug: Web/JavaScript/Reference/Global_Objects/Math/asin +tags: + - JavaScript + - Math + - Method + - Método(2) + - Reference + - Referência(2) +translation_of: Web/JavaScript/Reference/Global_Objects/Math/asin +--- +
{{JSRef}}
+ +

 

+ +

A função Math.asin() retorna o arco seno (em radianos) de um número, onde

+ +

x[-1;1],Math.asin(x)=arcsin(x)=o único valor y[-π2;π2]tal que sin(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

+ +

Sintaxe

+ +
Math.asin(x)
+ +

Parâmetros

+ +
+
x
+
Um número.
+
+ +

Valor retornado

+ +

O arco seno (em radianos) do parâmetro recebido se o parâmetro estiver entre -1 e 1; senão, {{jsxref("NaN")}}.

+ +

Descrição

+ +

O método Math.asin() retorna um valor numérico entre -π2-\frac{\pi}{2} e π2\frac{\pi}{2} radianos para todo x entre -1 e 1. Se o valor de x estiver fora deste intervalo {{jsxref("NaN")}} é retornado.

+ +

Por asin() ser um método estático de Math, deve-se sempre usá-lo como Math.asin(), e não como um método de um objeto Math que você criou.

+ +

Exemplos

+ +

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
+
+ +

Para valores menores que -1 ou maiores que 1, Math.asin() retorna {{jsxref("NaN")}}.

+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Definição inicial. Implementado no 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')}} 
+ +

Compatibilidade nos navegadores

+ + + +

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

+ +

Veja também

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

A função Math.asinh() retorna o arco-seno hiperbólico de um número, isto é:

+ +

Math.asinh(x)=arsinh(x)= the unique ysuch thatsinh(y)=x\mathtt{\operatorname{Math.asinh}(x)} = \operatorname{arsinh}(x) = \text{o} \; y \; \text{único tal que} \; \sinh(y) = x

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

Sintaxe

+ +
Math.asinh(x)
+ +

Parâmetros

+ +
+
x
+
Um número.
+
+ +

Valor de retorno

+ +

O arco-seno hiperbólico de um dado número.

+ +

Descrição

+ +

Como asinh() é um métodos estático de Math, você deve sempre chamá-lo como Math.asinh(), ao invés de um método de um objeto Math que você criou (Math não é um construtor).

+ +

Exemplos

+ +

Usando Math.asinh()

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

Polyfill

+ +

Como uma solução simples a expressçao\operatorname {arsinh} (x) = \ln \left(x + \sqrt{x^{2} + 1} \right) pode ser usada diretamente para uma emulação grosseira pela seguinte função:

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

Apesar de formalmente correta, ela sofre de algumas problemas relacionadas à computação de ponto flutuante. Resultados precisos precisam de tratamento especial de positivos/negativos e argumentos pequenos/grandes como feitos por exemplo em em glibc ouGNU Scientific Library.

+ +

Especificações

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

Compatibilitade de navegadores

+ + + +

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

+ +

Veja também

+ + diff --git a/files/pt-br/web/javascript/reference/global_objects/math/atan/index.html b/files/pt-br/web/javascript/reference/global_objects/math/atan/index.html new file mode 100644 index 0000000000..91e5b4f52a --- /dev/null +++ b/files/pt-br/web/javascript/reference/global_objects/math/atan/index.html @@ -0,0 +1,104 @@ +--- +title: Math.atan() +slug: Web/JavaScript/Reference/Global_Objects/Math/atan +tags: + - JavaScript + - Math + - Method + - Reference + - Referencia + - metodo +translation_of: Web/JavaScript/Reference/Global_Objects/Math/atan +--- +
{{JSRef}}
+ +

A função Math.atan() retorna a arco tangente (em radianos) de um número, onde

+ +

Math.atan(x)=arctan(x)= the unique y[-π2;π2]such thattan(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

+ +

Sintaxe

+ +
Math.atan(x)
+ +

Parâmetros

+ +
+
x
+
Um número.
+
+ +

Valor retornado

+ +

O arco tangente (em radianos) do parâmetro recebido.

+ +

Descrição

+ +

O método Math.atan() retorna um valor numérico entre -π2-\frac{\pi}{2} e π2\frac{\pi}{2} radianos.

+ +

Por atan() ser um método estático de Math, deve-se sempre usá-lo como Math.atan(), e não como um método de um objeto Math que você criou.

+ +

Exemplos

+ +

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
+
+// The angle that the line [(0,0);(x,y)] forms with the x-axis in a Cartesian coordinate system
+Math.atan(y / x);
+
+ +

Talvez você queira evitar usar ±Infinity por motivos estéticos. Nesse caso, {{jsxref("Math.atan2()")}} com 0 como segundo parâmentro pode ser uma solução melhor.

+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Definição inicial. Implementado em 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')}} 
+ +

Compatibilidade nos navegadores

+ + + +

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

+ +

Veja também

+ + diff --git a/files/pt-br/web/javascript/reference/global_objects/math/atan2/index.html b/files/pt-br/web/javascript/reference/global_objects/math/atan2/index.html new file mode 100644 index 0000000000..0c3b534c88 --- /dev/null +++ b/files/pt-br/web/javascript/reference/global_objects/math/atan2/index.html @@ -0,0 +1,150 @@ +--- +title: Math.atan2() +slug: Web/JavaScript/Reference/Global_Objects/Math/atan2 +translation_of: Web/JavaScript/Reference/Global_Objects/Math/atan2 +--- +
{{JSRef}}
+ +

A função Math.atan2() retorna o arco tangente do coeficiente dos argumentos passado.

+ +

Sintaxe

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

Parâmentros

+ +
+
y
+
Primeiro numero.
+
x
+
Segundo numero.
+
+ +

Retorno

+ +

O arco tagente do coegiente dos parâmetros

+ +

Descrição

+ +

Math.atan2() método retorna um valor numérico entre -π e π representando o ângulo teta entre (x, y).  Assim indo no sentido anti-horario ao ângulo, medido em radianos, entre o eixo X positivo, e o ponto(x, y).Nota os argumentos para essa função: primeiro o eixo Y(ordenadas) e o eixo X(absissas) como segundo parâmetro.

+ +

A simple diagram showing the angle returned by atan2(y, x)

+ +

Math.atan2()os argumentos são passados separados x e y enquanto no Math.atan() é passado a razão entre esses argumentos.

+ +

Porque atan2() é um método estático de  Math, você sempre usará  Math.atan2(), ao inves de um objeto Math criado (Math não é um construtor).

+ +

Examples

+ +

Using 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.
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial 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')}} 
{{SpecName('ESDraft', '#sec-math.atan2', 'Math.atan2')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

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

Veja também

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

A função Math.atanh() retorna o arco tangente hiperbólico de um número, onde

+ +

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{ the unique } \; y \; \text{such that} \; \tanh(y) = x

+ +

Sintaxe

+ +
Math.atanh(x)
+ +

Parâmetros

+ +
+
x
+
O número.
+
+ +

Valor retornado

+ +

O arco tangente hiperbólico do parâmetro recebido.

+ +

Descrição

+ +

Por atanh() ser um método estático de Math, deve-se sempre usá-lo como Math.atanh(), e não como um método de um objeto Math que você criou.

+ +

Exemplos

+ +

Usando Math.atanh()

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

For values greater than 1 or less than -1, {{jsxref("NaN")}} is returned.

+ +

Para valores menores que -1 ou maiores que 1, {{jsxref("NaN")}} é retornado.

+ +

Polyfill

+ +

Para |x|<1\left|x\right| < 1, temos artanh(x)=12ln(1+x1-x)\operatorname {artanh} (x) = \frac{1}{2}\ln \left( \frac{1 + x}{1 - x} \right), esse comportamento pode ser emulado com a seguinte função:

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

Especificações

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES6', '#sec-math.atanh', 'Math.atanh')}}{{Spec2('ES6')}}Definição inicial.
{{SpecName('ESDraft', '#sec-math.atanh', 'Math.atanh')}}{{Spec2('ESDraft')}} 
+ +

Compatibilidade no navegadores

+ + + +

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

+ +

Veja também

+ + diff --git a/files/pt-br/web/javascript/reference/global_objects/math/cbrt/index.html b/files/pt-br/web/javascript/reference/global_objects/math/cbrt/index.html new file mode 100644 index 0000000000..6c7ffcdf42 --- /dev/null +++ b/files/pt-br/web/javascript/reference/global_objects/math/cbrt/index.html @@ -0,0 +1,97 @@ +--- +title: Math.cbrt() +slug: Web/JavaScript/Reference/Global_Objects/Math/cbrt +tags: + - JavaScript + - Math + - Raiz Cúbica + - Referencia + - metodo +translation_of: Web/JavaScript/Reference/Global_Objects/Math/cbrt +--- +
{{JSRef}}
+ +

A função Math.cbrt() retorna a raiz cúbica de um número, isto é

+ +

Math.cbrt(x)=x3 = y, tal quey3=x\mathtt{Math.cbrt(x)} = \sqrt[3]{x} = \text{the unique} \; y \; \text{such that} \; y^3 = x

+ +

Sintaxe

+ +
Math.cbrt(x)
+ +

Parâmetros

+ +
+
x
+
Um número.
+
+ +

Valor de retorno

+ +

A raiz cúbica do número fornecido.

+ +

Descrição

+ +

Porque cbrt() é um método estático de Math, você sempre irá utilizar como Math.cbrt(), ao invés de um método de um objeto Math que você tenha criado (Math não é um construtor).

+ +

Exemplos

+ +

Utilizando Math.cbrt()

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

Polyfill

+ +

Para todo x0x \geq 0, temos x3=x1/3\sqrt[3]{x} = x^{1/3}, então isto pode ser simulado pela seguinte função:

+ +
if (!Math.cbrt) {
+  Math.cbrt = function(x) {
+    var y = Math.pow(Math.abs(x), 1/3);
+    return x < 0 ? -y : y;
+  };
+}
+
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('ES6', '#sec-math.cbrt', 'Math.cbrt')}}{{Spec2('ES6')}}Definição inicial
{{SpecName('ESDraft', '#sec-math.cbrt', 'Math.cbrt')}}{{Spec2('ESDraft')}} 
+ +

Compatibilidade

+ + + +

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

+ +

Veja também

+ + diff --git a/files/pt-br/web/javascript/reference/global_objects/math/ceil/index.html b/files/pt-br/web/javascript/reference/global_objects/math/ceil/index.html new file mode 100644 index 0000000000..68e48daa87 --- /dev/null +++ b/files/pt-br/web/javascript/reference/global_objects/math/ceil/index.html @@ -0,0 +1,210 @@ +--- +title: Math.ceil() +slug: Web/JavaScript/Reference/Global_Objects/Math/ceil +tags: + - JavaScript + - Math + - Method +translation_of: Web/JavaScript/Reference/Global_Objects/Math/ceil +--- +
{{JSRef("Global_Objects", "Math")}}
+ +

Resumo

+ +

A função Math.ceil(x) retorna o menor número inteiro maior ou igual a "x".

+ +

Sintaxe

+ +
Math.ceil(x) 
+ +

Parâmetros

+ +
+
x
+
Um número.
+
+ +

Valor de retorno

+ +

O menor inteiro maior ou igual ao número fornecido.

+ +

Descrição

+ +

Por ceil ser um método estático de Math, você sempre usará como Math.ceil(), e não como um método do objeto Math que você criou.

+ +

Exemplos

+ +

Usando Math.ceil()

+ +

O exemplo a seguir mostra um exemplo de 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(){
+
+	/**
+	 * Decimal adjustment of a number.
+	 *
+	 * @param	{String}	type	The type of adjustment.
+	 * @param	{Number}	value	The number.
+	 * @param	{Integer}	exp		The exponent (the 10 logarithm of the adjustment base).
+	 * @returns	{Number}			The adjusted value.
+	 */
+	function decimalAdjust(type, value, exp) {
+		// If the exp is undefined or zero...
+		if (typeof exp === 'undefined' || +exp === 0) {
+			return Math[type](value);
+		}
+		value = +value;
+		exp = +exp;
+		// If the value is not a number or the exp is not an integer...
+		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
+
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
ECMAScript 1st Edition. implementado em JavaScript 1.0PadrãoDefinição inicial.
{{SpecName('ES5.1', '#sec-15.8.2.6', 'Math.ceil')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-math.ceil', 'Math.ceil')}}{{Spec2('ES6')}}
+ +

Compatibilidade dos Browsers

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
RecursoChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte Básico{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
RecursoAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte Básico{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/javascript/reference/global_objects/math/clz32/index.html b/files/pt-br/web/javascript/reference/global_objects/math/clz32/index.html new file mode 100644 index 0000000000..c997e014ec --- /dev/null +++ b/files/pt-br/web/javascript/reference/global_objects/math/clz32/index.html @@ -0,0 +1,179 @@ +--- +title: Math.clz32() +slug: Web/JavaScript/Reference/Global_Objects/Math/clz32 +tags: + - JavaScript + - Math + - sintaxe Math.clz32() +translation_of: Web/JavaScript/Reference/Global_Objects/Math/clz32 +--- +
{{JSRef}}
+ +

A função Math.clz32 () retorna o número de zero bit inicial na representação binária de 32 bits de um número.

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

Sintaxe

+ +
Math.clz32(x)
+ +

Parâmetros

+ +
+
x
+
Um número.
+
+ +

Valor de retorno

+ +

O número de zero bits à esquerda na representação binária de 32 bits do número fornecido.

+ +

Descrição

+ +

"clz32" é short paraCountLeadingZeroes32.

+ +

Se x não for um número, ele será convertido em um número primeiro e depois convertido em um número inteiro não assinado de 32 bits.

+ +

Se o número inteiro não assinado de 32 bits convertido for 0, retorne 32, porque todos os bits são 0.

+ +

Essa função é particularmente útil para sistemas que são compilados para JS, como o Emscripten.

+ +

Exemplos

+ +

Usando Math.clz32()

+ +
Math.clz32(1);           // 31
+Math.clz32(1000);        // 22
+Math.clz32();            // 32
+
+var stuff = [NaN, Infinity, -Infinity, 0, -0, null, undefined, 'foo', {}, []];
+stuff.every(n => Math.clz32(n) == 32);  // true
+
+Math.clz32(true);        // 31
+Math.clz32(3.5);         // 30
+ +

Contagem dos principais e mais além

+ +

No momento, não há Math.clon para "Count Leading Ones" (chamado "clon", não "clo", porque "clo" e "clz" são muito semelhantes, especialmente para pessoas que não falam inglês). No entanto, uma função clon pode ser criada facilmente, invertendo os bits de um número e passando o resultado para Math.clz32. Fazer isso funcionará porque o inverso de 1 é 0 e vice-versa. Assim, a inversão dos bits inverterá a quantidade medida de 0s (de Math.clz32), fazendo com que Math.clz32 conte o número de unidades em vez de contar o número de zeros.

+ +

Considere a seguinte palavra de 32 bits:

+ +
var a = 32776;   // 00000000000000001000000000001000 (16 zeros à esquerda)
+Math.clz32(a);   // 16
+
+var b = ~32776;  // 11111111111111110111111111110111 (32776 inverso, 0 zeros à esquerda)
+Math.clz32(b);   // 0 (isso é igual a quantos líderes existem em um)
+ +

Usando essa lógica, uma função clon pode ser criada da seguinte maneira:

+ +
var clz = Math.clz32;
+function clon(integer){
+    return clz(~integer);
+}
+
+ +

Além disso, essa técnica pode ser estendida para criar funções inumeráveis "Contagem de zeros à direita" e funções de contagem de zeros, como mostrado abaixo. A função ctrz abaixo preenche todos os bits altos com o bit mais baixo preenchido e depois os anula para apagar todos os bits mais altos definidos, de modo que o clz possa ser usado.

+ +
var clz = Math.clz32;
+function ctrz(integer){ // contar zeros à direita
+   // 1. preencha todos os bits mais altos após o primeiro
+    integer |= integer << 16;
+    integer |= integer << 8;
+    integer |= integer << 4;
+    integer |= integer << 2;
+    integer |= integer << 1;
+// 2. Agora, a inversão dos bits revela os bits mais baixos
+    return 32 - clz(~integer) |0; // `|0`garante coerção inteira
+}
+function ctron(integer){ // conta os que estão à direita
+     // Nenhum operador shift-fill-in-with-ones está disponível em
+     // JavaScript, portanto, o código abaixo é o mais rápido
+    return ctrz(~integer);
+/ * Implementação alternativa para fins demonstrativos:
+        // 1. apaga todos os bits mais altos após o primeiro zero
+       integer &= (integer << 16) | 0xffff;
+       integer &= (integer << 8 ) | 0x00ff;
+       integer &= (integer << 4 ) | 0x000f;
+       integer &= (integer << 2 ) | 0x0003;
+       integer &= (integer << 1 ) | 0x0001;
+      // 2. Agora, reverter os bits revela os zeros mais baixos
+       return 32 - clon(~integer) |0;
+    */
+}
+
+ +

Transforme essas funções auxiliares no módulo ASM.JS; então, você tem uma verdadeira obra-prima de desempenho. Situações como essas são exatamente para o que o ASM.JS foi projetado.

+ +
var countTrailsMethods = (function(stdlib, foreign, heap) {
+    "use asm";
+    var clz = stdlib.Math.clz32;
+    function ctrz(integer) { // count trailing zeros
+        integer = integer | 0; // coerce to an integer
+// 1. preencha todos os bits mais altos após o primeiro
+// ASM js, por algum motivo, não permite ^ =, & = ou | =
+        integer = integer | (integer << 16);
+        integer = integer | (integer << 8);
+        integer = integer | (integer << 4);
+        integer = integer | (integer << 2);
+        integer = integer | (integer << 1);
+      // 2. Agora, a inversão dos bits revela os bits mais baixos
+        return 32 - clz(~integer) |0;
+    }
+    function ctron(integer) { //contar os últimos
+        integer = integer | 0; // coagir a um número inteiro
+        return ctrz(~integer) |0;
+    }
+// infelizmente, o ASM.JS exige objetos compactos lentos:
+    return {a: ctrz, b: ctron};
+})(window, null, null);
+var ctrz = countTrailsMethods.a;
+var ctron = countTrailsMethods.b;
+ +

Polyfill-"Trecho de código"

+ +

O seguinte polyfill é o mais eficiente.

+ +
if (!Math.clz32) Math.clz32 = (function(log, LN2){
+  return function(x) {
+ // Seja n ToUint32 (x).
+     // Seja p o número de zero bits iniciais em
+     // a representação binária de 32 bits de n.
+     // Retornar p.
+    var asUint = x >>> 0;
+    if (asUint === 0) {
+      return 32;
+    }
+    return 31 - (log(asUint) / LN2 | 0) |0; // the "| 0" acts like math.floor
+  };
+})(Math.log, Math.LN2);
+
+ +

Especificações

+ + + + + + + + + + + + +
Especificação
{{SpecName('ESDraft', '#sec-math.clz32', 'Math.clz32')}}
+ +

Compatibilidade do navegador

+ + + +

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

+ +

Veja também

+ + diff --git a/files/pt-br/web/javascript/reference/global_objects/math/cos/index.html b/files/pt-br/web/javascript/reference/global_objects/math/cos/index.html new file mode 100644 index 0000000000..c0b0662477 --- /dev/null +++ b/files/pt-br/web/javascript/reference/global_objects/math/cos/index.html @@ -0,0 +1,102 @@ +--- +title: Math.cos() +slug: Web/JavaScript/Reference/Global_Objects/Math/cos +tags: + - Geometria + - JavaScript + - Matemática + - Math + - Trigonometría + - cos + - cosseno + - metodo +translation_of: Web/JavaScript/Reference/Global_Objects/Math/cos +--- +
{{JSRef}}
+ +

 A função Math.cos() ,que é estatica, retorna o {{interwiki("wikipedia", "cosseno")}} de um ângulo, que deve estar em {{interwiki("wikipedia", "radianos")}}. A expressão é length adjacent length hypotenuse . 

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

Sintaxe

+ +
Math.cos(x)
+ +

Parâmetros

+ +
+
x
+
Ângulo em radianos
+
+ +

Valor de retorno

+ +

O cosseno do número: x

+ +

Descrição

+ +

Math.cos() é um método que retorna um número entre -1 e 1, que representa o cosseno de um ângulo.

+ +

Já que cos() é um método estático de Math, você sempre deve usar Math.cos(), ao invez de criar um objeto de Math (Math não tem construtor).

+ +

Exemplos

+ +

Usando Math.cos()

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

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.8.2.7', 'Math.cos')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math.cos', 'Math.cos')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-math.cos', 'Math.cos')}}{{Spec2('ESDraft')}} 
+ +

Compatibilidade dos Browsers

+ + + +

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

+ +

Veja também

+ + diff --git a/files/pt-br/web/javascript/reference/global_objects/math/cosh/index.html b/files/pt-br/web/javascript/reference/global_objects/math/cosh/index.html new file mode 100644 index 0000000000..f6e0671abd --- /dev/null +++ b/files/pt-br/web/javascript/reference/global_objects/math/cosh/index.html @@ -0,0 +1,88 @@ +--- +title: Math.cosh() +slug: Web/JavaScript/Reference/Global_Objects/Math/cosh +translation_of: Web/JavaScript/Reference/Global_Objects/Math/cosh +--- +
{{JSRef}}
+ +

A função Math.cosh() retorna o cosseno hiperbólico de um número, que pode ser expressada usando {{jsxref("Math.E", "constante e", "", 1)}}:

+ +

Math.cosh(x)=ex+e-x2\mathtt{\operatorname{Math.cosh(x)}} = \frac{e^x + e^{-x}}{2}

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

Sintaxe

+ +
Math.cosh(x)
+ +

Parâmetros

+ +
+
x
+
  Um número.
+
+ +

Valor de retorno

+ +

O cosseno hiperbólico do número dado.

+ +

Descrição

+ +

Por cosh() ser um método estático de Math, sempre utilize como Math.cosh(), ao invés de como um método de um objeto Math que você criou (Math não é um construtor).

+ +

Exemplos

+ +

Usando Math.cosh()

+ +
Math.cosh(0);  // 1
+Math.cosh(1);  // 1.5430806348152437
+Math.cosh(-1); // 1.5430806348152437
+
+ +

Polyfill

+ +

Isto pode ser emulado com a ajuda da função {{jsxref("Math.exp()")}}:

+ +
Math.cosh = Math.cosh || function(x) {
+  return (Math.exp(x) + Math.exp(-x)) / 2;
+}
+
+ +

ou usando apenas uma chamada da função {{jsxref("Math.exp()")}}:

+ +
Math.cosh = Math.cosh || function(x) {
+  var y = Math.exp(x);
+  return (y + 1 / y) / 2;
+};
+
+ +

Especificações

+ + + + + + + + + + +
Especificações
{{SpecName('ESDraft', '#sec-math.cosh', 'Math.cosh')}}
+ +

Compatibilidade com Navegadores

+ + + +

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

+ +

See also

+ + diff --git a/files/pt-br/web/javascript/reference/global_objects/math/e/index.html b/files/pt-br/web/javascript/reference/global_objects/math/e/index.html new file mode 100644 index 0000000000..36b01b0430 --- /dev/null +++ b/files/pt-br/web/javascript/reference/global_objects/math/e/index.html @@ -0,0 +1,86 @@ +--- +title: Math.E +slug: Web/JavaScript/Reference/Global_Objects/Math/E +tags: + - JavaScript + - Math + - Propriedade + - Referencia +translation_of: Web/JavaScript/Reference/Global_Objects/Math/E +--- +
{{JSRef}}
+ +

A propriedade Math.E representa a base dos logarítmos naturais, 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)}}
+ +

Descrição

+ +

Como E é uma propriedade estática de Math, sempre use-a como Math.E, ao invés de uma propriedade de um objeto Math que você criou (Math não é um construtor).

+ +

Exemplos

+ +

Usando Math.E

+ +

A seguinte função retorna o valor de e:

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

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('ES1')}}{{Spec2('ES1')}}Definição inicial. Implementado no 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')}} 
+ +

Compatibilidade de navegadores

+ + + +

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

+ +

Veja também

+ + diff --git a/files/pt-br/web/javascript/reference/global_objects/math/exp/index.html b/files/pt-br/web/javascript/reference/global_objects/math/exp/index.html new file mode 100644 index 0000000000..279cb1b60b --- /dev/null +++ b/files/pt-br/web/javascript/reference/global_objects/math/exp/index.html @@ -0,0 +1,109 @@ +--- +title: Math.exp() +slug: Web/JavaScript/Reference/Global_Objects/Math/exp +tags: + - JavaScript + - Math + - Method +translation_of: Web/JavaScript/Reference/Global_Objects/Math/exp +--- +
+ {{JSRef("Global_Objects", "Math")}}
+

Sumário

+

A função Math.exp() retorna ex, onde x é o argumento, e e é a Constante de Euler, a base dos logaritmos naturais

+

Síntaxe

+
Math.exp(x)
+

Parâmetros

+
+
+ x
+
+ Um número.
+
+

Descrição

+

Pelo fato de exp ser um método estático de Math, você sempre utiliza-o como Math.exp(), não como um método do objeto Math que você criou.

+

Exemplos

+

Exemplo: Usando Math.exp

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

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
1ª Edição ECMAScript 1st Edition. Implementado em JavaScript 1.0PadrãoDefinição Inicial.
{{SpecName('ES5.1', '#sec-15.8.2.8', 'Math.exp')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math.exp', 'Math.exp')}}{{Spec2('ES6')}} 
+

Compatibilidade de navegadores

+

{{ CompatibilityTable() }}

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

Veja também

+ diff --git a/files/pt-br/web/javascript/reference/global_objects/math/expm1/index.html b/files/pt-br/web/javascript/reference/global_objects/math/expm1/index.html new file mode 100644 index 0000000000..0dfe3aab94 --- /dev/null +++ b/files/pt-br/web/javascript/reference/global_objects/math/expm1/index.html @@ -0,0 +1,80 @@ +--- +title: Math.expm1() +slug: Web/JavaScript/Reference/Global_Objects/Math/expm1 +translation_of: Web/JavaScript/Reference/Global_Objects/Math/expm1 +--- +
{{JSRef}}
+ +

The Math.expm1() function returns ex - 1, where x is the argument, and {{jsxref("Math.E", "e", "", 1)}} the base of the natural logarithms.

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

Syntax

+ +
Math.expm1(x)
+ +

Parameters

+ +
+
x
+
Um número.
+
+ +

Return value

+ +

Um número representando ex - 1, onde e é {{jsxref("Math.E", "Euler's number", "", 1)}} e x ié o argumento.

+ +

Description

+ +

Porque expm1() é um método estático de is Math, você sempre o usurá como Math.expm1(), do que como um método de um objeto Math que você criou (Math não é um contrutor).

+ +

Polyfill

+ +

This can be emulated with the help of the {{jsxref("Math.exp()")}} function:

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

Examples

+ +

Using Math.expm1()

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

Specifications

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

Browser compatibility

+ + + +

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

+ +

See also

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

Resumo

+ +

A função Math.floor(x) retorna o menor número inteiro dentre o número "x".

+ +

Sintaxe

+ +
Math.floor(x) 
+ +

Parâmetros

+ +
+
x
+
Um número.
+
+ +

Descrição

+ +

Por floor ser um método estático de Math, você sempre irá usar como Math.floor(),e não como método do objeto Math que você criou.

+ +

Exemplos

+ +

Exemplo: Usando Math.floor

+ +
Math.floor( 45.95); //  45
+Math.floor(-45.95); // -46
+
+ +

Exemplo: Ajuste Decimal

+ +
// Closure
+(function(){
+
+	/**
+	 * Decimal adjustment of a number.
+	 *
+	 * @param	{String}	type	The type of adjustment.
+	 * @param	{Number}	value	The number.
+	 * @param	{Integer}	exp		The exponent (the 10 logarithm of the adjustment base).
+	 * @returns	{Number}			The adjusted value.
+	 */
+	function decimalAdjust(type, value, exp) {
+		// If the exp is undefined or zero...
+		if (typeof exp === 'undefined' || +exp === 0) {
+			return Math[type](value);
+		}
+		value = +value;
+		exp = +exp;
+		// If the value is not a number or the exp is not an integer...
+		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
+
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
ECMAScript 1st Edition. Implemented in JavaScript 1.0StandardInitial definition.
{{SpecName('ES5.1', '#sec-15.8.2.9', 'Math.floor')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math.floor', 'Math.floor')}}{{Spec2('ES6')}} 
+ +

Compatibilidade dos Browsers

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/javascript/reference/global_objects/math/hypot/index.html b/files/pt-br/web/javascript/reference/global_objects/math/hypot/index.html new file mode 100644 index 0000000000..b83197c861 --- /dev/null +++ b/files/pt-br/web/javascript/reference/global_objects/math/hypot/index.html @@ -0,0 +1,115 @@ +--- +title: Math.hypot() +slug: Web/JavaScript/Reference/Global_Objects/Math/hypot +tags: + - JavaScript + - Math + - Method + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Math/hypot +--- +
{{JSRef}}
+ +

A função Math.hypot() retorna a raiz quadrada do somátorio do quadrado de seus parâmetros, ou seja

+ +

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}

+ +

Sintaxe

+ +
Math.hypot([value1[, value2[, ...]]])
+ +

Parâmetros

+ +
+
value1, value2, ...
+
Números.
+
+ +

Valor retornado

+ +

A raiz quadrada do somátorio do quadrado dos parâmetros recebidos. Se um ou mais argumentos não puderem ser convertidos para um número, {{jsxref("NaN")}} é retornado.

+ +

Descrição

+ +

Para calcular a hipotenusa de um triângulo retângulo, ou o módulo de um número complexo, é usada a fórmula Math.sqrt(v1*v1 + v2*v2) (v12+v22\sqrt{v1^2 + v2^2}) onde v1 e v2 são, ou os lados de um triângulo, ou a parte real e a imaginário de um número complexo. Para calcular a distância entre duas ou mais dimensões, basta adicionar mais exponenciações dentro da raiz quadrada, por exemplo Math.sqrt(v1*v1 + v2*v2 + v3*v3 + v4*v4) (v12+v22+v32+v42\sqrt{v1^2 + v2^2 + v3^2 + v4^2}).

+ +

A função Math.hypot() torna esta tarefa mais rápida e mais fácil, basta executar Math.hypot(v1, v2) , or Math.hypot(v1, v2, v3, v4, ...) .

+ +

Dessa maneira também se evita problemas se a magnitude dos seus número for muito grande. O maio número que se pode representar em um double float em JavasScript é Number.MAX_VALUE = 1.797...e+308. Se os seu números são maior que 1e154, calcular o quadrado deles resultará em Infinity, estragando os seus resultados. Por exemplo, Math.sqrt(1e200*1e200 + 1e200*1e200) = Infinity. Se você usar a função Math.hypot(), você receberá uma resposta aceitável: Math.hypot(1e200, 1e200) = 1.4142...e+200. Isto também é verdade para número muito pequenos. Math.sqrt(1e-200*1e-200 + 1e-200*1e-200) = 0, mas Math.hypot(1e-200, 1e-200) = 1.4142...e-200 é uma boa resposta.

+ +
+

Por hypot() ser um método estático de Math, deve-se sempre usá-lo como Math.hypot(), e não como um método de um objeto Math que você criou.

+
+ +

Se nenhum parâmetro for passado, o resultado é +0.

+ +

Se um ou mais parâmetros não puderem ser convertidos para um número, o resultado será {{jsxref("NaN")}}.

+ +

Com apenas um parâmetro, Math.hypot() se comporta como Math.abs().

+ +

Examples

+ +

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, the same as Math.abs(-3)
+
+ +

Polyfill

+ +

O comportamento de Math.hypot() pode ser emulado com a seguinte função:

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

Especificações

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-math.hypot', 'Math.hypot')}}{{Spec2('ES2015')}}Definição inicial.
{{SpecName('ESDraft', '#sec-math.hypot', 'Math.hypot')}}{{Spec2('ESDraft')}} 
+ +

Compatibilidade no navegador

+ + + +

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

+ +

Ver também

+ + diff --git a/files/pt-br/web/javascript/reference/global_objects/math/index.html b/files/pt-br/web/javascript/reference/global_objects/math/index.html new file mode 100644 index 0000000000..47bbf2f3cb --- /dev/null +++ b/files/pt-br/web/javascript/reference/global_objects/math/index.html @@ -0,0 +1,208 @@ +--- +title: Math +slug: Web/JavaScript/Reference/Global_Objects/Math +tags: + - JavaScript + - Math + - NeedsTranslation + - TopicStub +translation_of: Web/JavaScript/Reference/Global_Objects/Math +--- +
{{JSRef("Global_Objects", "Math")}}
+ +

Math é um objeto embutido que tem propriedades e métodos para constantes e funções matemáticas. Não é um objeto de função.

+ +

Descrição

+ +

Ao contrário de outros objetos globais, Math não é um construtor. Todas as propriedades e métodos de Math são estáticos. Você pode referenciar a constante PI como Math.PI e você pode chamar a função de seno como Math.sin(x), onde x  é o argumento do método. Constantes são definidas com a precisão total de números reais em JavaScript.

+ +

Propriedades

+ +
+
{{jsxref("Math.E")}}
+
Constante de Euler e base dos logaritmos naturais, 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 na base 2, aproximadamente 1.443.
+
{{jsxref("Math.LOG10E")}}
+
Logaritmo de E na base 10, aproximadamente 0.434.
+
{{jsxref("Math.PI")}}
+
Relação entre a circunferência de um círculo e o seu diâmetro, aproximadamente 3.14159.
+
{{jsxref("Math.SQRT1_2")}}
+
Raiz quadrada de 1/2; Equivale a 1 dividido pela raiz quadrada de 2, aproximadamente 0.707.
+
{{jsxref("Math.SQRT2")}}
+
Raiz quadrada de 2, aproximadamente 1.414.
+
+ +
{{ jsOverrides("Object", "properties", "E", "LN2", "LN10", "LOG2E", "LOG10E", "PI", "SQRT1_2", "SQRT") }}
+ +

Métodos

+ +
Note que as funções trigonométricas (sin(), cos(), tan(), asin(), acos(), atan(), atan2()) recebem ou retornam ângulos em radianos. Divida por (Math.PI/180) para converter radianos em graus, ou multiplique por esse valor para fazer a conversão inversa.
+ +
+
{{jsxref("Global_Objects/Math/abs", "Math.abs(x)")}}
+
Retorna o módulo, ou valor absoluto, de um número (|x||x|).
+
{{jsxref("Global_Objects/Math/acos", "Math.acos(x)")}}
+
Retorna o arco-coseno de um número (arccosx\arccos{x}).
+
{{jsxref("Global_Objects/Math/acosh", "Math.acosh(x)")}} {{experimental_inline}}
+
Retorna o arco-coseno hiperbólico de um número.
+
{{jsxref("Global_Objects/Math/asin", "Math.asin(x)")}}
+
Retorna o arco-seno de um número (arcsinx\arcsin{x}).
+
{{jsxref("Global_Objects/Math/asinh", "Math.asinh(x)")}} {{experimental_inline}}
+
Retorna o arco-seno hiperbólico de um número.
+
{{jsxref("Global_Objects/Math/atan", "Math.atan(x)")}}
+
Retorna o arco-tangente de um número (arctanx\arctan{x}).
+
{{jsxref("Global_Objects/Math/atanh", "Math.atanh(x)")}} {{experimental_inline}}
+
Retorna o arco-tangente hiperbólico de um número (arctanx\arctan{x}).
+
{{jsxref("Global_Objects/Math/atan2", "Math.atan2(x, y)")}}
+
Retorna o arco-tangente do quociente de seus argumentos.
+
{{jsxref("Global_Objects/Math/cbrt", "Math.cbrt(x)")}} {{experimental_inline}}
+
Retorna a raiz cúbica de um número (x3\root{3}{x}).
+
{{jsxref("Global_Objects/Math/ceil", "Math.ceil(x)")}}
+
Retorna o menor inteiro que é maior ou igual a um número.
+
{{jsxref("Global_Objects/Math/cos", "Math.cos(x)")}}
+
Retorna o coseno de um número (cosx\cos{x}).
+
{{jsxref("Global_Objects/Math/cosh", "Math.cosh(x)")}} {{experimental_inline}}
+
Retorna o coseno hiperbólico de um número .
+
{{jsxref("Global_Objects/Math/exp", "Math.exp(x)")}}
+
Retorna exe^x, onde x é o argumento, e ee é a constante de Euler (2.718...), a base do logaritmo natural.
+
{{jsxref("Global_Objects/Math/expm1", "Math.expm1(x)")}} {{experimental_inline}}
+
Retorna ex-1e^x-1.
+
{{jsxref("Global_Objects/Math/floor", "Math.floor(x)")}}
+
Retorna o maior inteiro que é menor ou igual a um número.
+
{{jsxref("Global_Objects/Math/fround", "Math.fround(x)")}} {{experimental_inline}}
+
Retorna a mais próxima representação de ponto flutuante de precisão-única de um número.
+
{{jsxref("Global_Objects/Math/hypot", "Math.hypot([x[,y[,…]]])")}} {{experimental_inline}}
+
Retorna a raiz quadrada da soma dos quadrados dos argumentos (x2+y2+\sqrt{x^2 + y^2 + \dots}).
+
{{jsxref("Global_Objects/Math/imul", "Math.imul(x)")}} {{experimental_inline}}
+
Retorna o resultado de uma multiplicação de inteiro de 32-bit.
+
{{jsxref("Global_Objects/Math/log", "Math.log(x)")}}
+
Retorna o logaritmo natural (logex\log_ex ou lnx\ln{x}) de um número.
+
{{jsxref("Global_Objects/Math/log1p", "Math.log1p(x)")}} {{experimental_inline}}
+
Retorna o logaritmo natural de 1 + x (loge(1+x)\log_e(1+x) ou ln(1+x)\ln(1+x)) de um número.
+
{{jsxref("Global_Objects/Math/log10", "Math.log10(x)")}} {{experimental_inline}}
+
Retorna o logaritmo de x na base 10 (log10x\log_{10}x).
+
{{jsxref("Global_Objects/Math/log2", "Math.log2(x)")}} {{experimental_inline}}
+
Retorna o logaritmo de x na base 2 (log2x\log_2 x).
+
{{jsxref("Global_Objects/Math/max", "Math.max([x[,y[,…]]])")}}
+
Retorna o maior dentre os parâmetros recebidos.
+
{{jsxref("Global_Objects/Math/min", "Math.min([x[,y[,…]]])")}}
+
Retorna o menor dentre os parâmetros recebidos.
+
{{jsxref("Global_Objects/Math/pow", "Math.pow(x,y)")}}
+
Retorna a base x elevada à potência y do expoente, ou seja, xyx^y.
+
{{jsxref("Global_Objects/Math/random", "Math.random()")}}
+
Retorna um número pseudo-aleatório entre 0 e 1.
+
{{jsxref("Global_Objects/Math/round", "Math.round(x)")}}
+
Retorna o valor arrendodado de x, para o valor inteiro mais próximo.
+
{{jsxref("Global_Objects/Math/sign", "Math.sign(x)")}} {{experimental_inline}}
+
Retorna o sinal de x, indicando se é positivo, negativo ou zero.
+
{{jsxref("Global_Objects/Math/sin", "Math.sin(x)")}}
+
Retorna o seno de um número (sinx\sin x).
+
{{jsxref("Global_Objects/Math/sinh", "Math.sinh(x)")}} {{experimental_inline}}
+
Retorna o seno hiperbólico de um número (sinhx\sinh x).
+
{{jsxref("Global_Objects/Math/sqrt", "Math.sqrt(x)")}}
+
Retorna a raiz quadrada positiva de um número (x\sqrt x).
+
{{jsxref("Global_Objects/Math/tan", "Math.tan(x)")}}
+
Retorna a tangente de um número (tanx\tan x).
+
{{jsxref("Global_Objects/Math/tanh", "Math.tanh(x)")}} {{experimental_inline}}
+
Retorna a tangente hiperbólica de um número (tanhx\tanh x).
+
Math.toSource() {{Non-standard_inline() }}
+
Retorna a string "Math".
+
{{jsxref("Global_Objects/Math/trunc", "Math.trunc(x)")}} {{experimental_inline}}
+
Retorna a parte inteira de x, removendo quaisquer dígitos fracionários.
+
+ +
{{ jsOverrides("Object", "Methods") }}
+ +
+

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('ES1')}}{{Spec2('ES1')}}Definição inicial, implementado no JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.8', 'Math')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math-object', 'Math')}}{{Spec2('ES6')}}Novos métodos adicionados: {{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()")}} e {{jsxref("Math.clz32()", "clz32()")}}
+ +

Compatibilidade nos navegadores

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
ConteúdoChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
ConteúdoAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +

Veja também

+ + +
+ +

 

diff --git a/files/pt-br/web/javascript/reference/global_objects/math/ln10/index.html b/files/pt-br/web/javascript/reference/global_objects/math/ln10/index.html new file mode 100644 index 0000000000..a5df5d4e52 --- /dev/null +++ b/files/pt-br/web/javascript/reference/global_objects/math/ln10/index.html @@ -0,0 +1,121 @@ +--- +title: Math.LN10 +slug: Web/JavaScript/Reference/Global_Objects/Math/LN10 +translation_of: Web/JavaScript/Reference/Global_Objects/Math/LN10 +--- +
{{JSRef}}
+ +

A propriedade Math.LN10 representa o logaritmo natural de 10, aproximadamente 2.302:

+ +

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

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

Descrição

+ +

Como LN10 é uma propriedade estática de Math,  você sempre deve usa-lo como Math.LN10, ao invés de uma propriedade do objeto Math que você tenha criado (Math não é um construtor).

+ +

Exemplos

+ +

Usando Math.LN10

+ +

A seguinte função retorna o log natural de 10:

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

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('ES1')}}{{Spec2('ES1')}}Definição inicial. Implementado em 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')}} 
+ +

Compatibilidade com navegadores

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
RecursoChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Veja também

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

A propriedade Math.LN2 representa o logaritmo natural (também conhecido como logaritmo neperiano) de 2, que é aproximadamente 0.693:

+ +

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

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

Descrição

+ +

Por LN2 ser uma propriedade estática de Math, deve-se sempre usá-la como Math.LN2, e não como uma propriedade de um objeto Math que você criou.

+ +

Exemplos

+ +

Usando Math.LN2

+ +

A função a seguir retorna o logaritmo natural de 2:

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

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in 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')}} 
+ +

Compatibilidade dos navegadores

+ + + +

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

+ +

Veja também

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

A função  Math.log() retorna o logaritmo natural(base {{jsxref("Math.E", "e")}}) de um número, que é:

+ +

x>0,Math.log(x)=ln(x)=the uniqueysuch thatey=x\forall x > 0, \mathtt{\operatorname{Math.log}(x)} = \ln(x) = \text{the unique} \; y \; \text{such that} \; e^y = x

+ +

Sintaxe

+ +
Math.log(x)
+ +

Parâmetros

+ +
+
x
+
Um número.
+
+ +

Retorno

+ +

O logaritmo natural (base {{jsxref("Math.E", "e")}}) de um número dado. Se o número é negativo, {{jsxref("NaN")}} é retornado.

+ +

Descrição

+ +

Se o valor de  x é negativo, o retorno será sempre {{jsxref("NaN")}}.

+ +

Por log() ser um método estático de Math, você sempre o usará como Math.log(), ao invés de um método de um objeto de Math que você criou(Math não é um construtor).

+ +

Caso você precise do logaritmo natural de 2 ou 10, use as constantes {{jsxref("Math.LN2")}} ou {{jsxref("Math.LN10")}} .  Caso você precise de um logaritmo de base 2 ou 10, use {{jsxref("Math.log2()")}} ou {{jsxref("Math.log10()")}} .  Caso você precise utilizar logaritmo de outras bases, use Math.log(x) / Math.log(outraBase) como no exemplo abaixo; talvez você queira pré-calcular 1 / Math.log(outraBase) .

+ +

Exemplos

+ +

Usando Math.log()

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

Usando Math.log() como uma base diferente

+ +

As funções a seguir retornam o logaritmo de y na base x (ie. logxy\log_x y):

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

Caso você execute getBaseLog(10, 1000) será retornado 2.9999999999999996 devido ao arredondamento de ponto-flutuante, o qual é bem próximo do retorno exato de 3.

+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Definição inicial. Implementado no 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')}} 
+ +

Compatibilidade de navegadores

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

Veja também

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

A função Math.log10() retorna o logaritmo de base 10 de um número, que é

+ +

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

+ +

Sintaxe

+ +
Math.log10(x)
+ +

Parâmetros

+ +
+
x
+
Um número.
+
+ +

Retorno

+ +

O logaritmo de base 10 de um número. Caso o número seja negativo, {{jsxref("NaN")}} é retornado.

+ +

Descrição

+ +

Caso o valor de x seja menor que 0, então o retorno será sempre {{jsxref("NaN")}}.

+ +

Por log10() ser um método estático de Math, você sempre o usará como Math.log10(), ao invés de usá-lo como método de um objeto Math criado (Math não é um construtor).

+ +

Esta função é equivalente a Math.log(x) / Math.log(10).  Para log10(e) use a constante {{jsxref("Math.LOG10E")}} que é 1 / {{jsxref("Math.LN10")}}.  

+ +

Exemplos

+ +

Usando Math.log10()

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

Polyfill

+ +

Isso pode ser simulado a partir da seguinte função:

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

Especificações

+ + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('ES6', '#sec-math.log10', 'Math.log10')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-math.log10', 'Math.log10')}}{{Spec2('ESDraft')}} 
+ +

Compatibilidade de navegadores

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FuncionalidadeChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{CompatChrome("38")}}{{CompatGeckoDesktop("25")}}{{CompatNo}}{{CompatOpera("25")}}{{CompatSafari("7.1")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FuncionalidadeAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile("25")}}{{CompatNo}}{{CompatNo}}8
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/javascript/reference/global_objects/math/log10e/index.html b/files/pt-br/web/javascript/reference/global_objects/math/log10e/index.html new file mode 100644 index 0000000000..1c2f57c178 --- /dev/null +++ b/files/pt-br/web/javascript/reference/global_objects/math/log10e/index.html @@ -0,0 +1,82 @@ +--- +title: Math.LOG10E +slug: Web/JavaScript/Reference/Global_Objects/Math/LOG10E +tags: + - JavaScript + - Math + - Property + - Propriedade + - Referece + - Referência(2) +translation_of: Web/JavaScript/Reference/Global_Objects/Math/LOG10E +--- +
{{JSRef}}
+ +

A propriedade Math.LOG10E representa o logaritmo com base 10 de e, 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)}}
+ +

Descrição

+ +

Por LOG10E ser uma propriedade estática de Math, deve-se sempre usá-la como Math.LOG10E, e não como propriedade de um objeto Math criado por você (Math não é um construtor).

+ +

Exemplos

+ +

Usando Math.LOG10E

+ +

A função a seguir retorna o logaritmo com base 10 de e:

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

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in 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')}} 
+ +

Compatibilidade no navegadores

+ + + +

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

+ +

Veja também

+ + diff --git a/files/pt-br/web/javascript/reference/global_objects/math/log1p/index.html b/files/pt-br/web/javascript/reference/global_objects/math/log1p/index.html new file mode 100644 index 0000000000..b36c74ff62 --- /dev/null +++ b/files/pt-br/web/javascript/reference/global_objects/math/log1p/index.html @@ -0,0 +1,105 @@ +--- +title: Math.log1p() +slug: Web/JavaScript/Reference/Global_Objects/Math/log1p +tags: + - ECMAScript 2015 + - JavaScript + - Logaritmo Natural + - Math + - Math.log1p + - Referencia + - metodo +translation_of: Web/JavaScript/Reference/Global_Objects/Math/log1p +--- +
{{JSRef}}
+ +

A função Math.log1p()  returna o logaritmo natural (base {{jsxref("Math.E", "e")}}) de 1 + um número, isto é

+ +

x>-1,Math.log1p(x)=ln(1+x)\forall x > -1, \mathtt{\operatorname{Math.log1p}(x)} = \ln(1 + x)

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

Sintaxe

+ +
Math.log1p(x)
+ +

Parâmetros

+ +
+
x
+
Um número.
+
+ +

Valor de retorno

+ +

O logaritmo natural (base {{jsxref("Math.E", "e")}}) de 1 mais o número fornecido. Se o número for menor que -1, {{jsxref("NaN")}} será retornado.

+ +

Descrição

+ +

Para valores muito pequenos de x, adicionando 1 pode reduzir ou eliminar precisão. Valores double floats costuman te dar em torno de 15 digitos de precisão no JavaScript. 1 + 1e-15 = 1.000000000000001, porém, 1 + 1e-16 = 1.000000000000000 e portanto, exatamente 1.0 naquele resultado, porque os números que passam de 15 digitos são arredondados.

+ +

Quando você calcula log(1 + x), você obterá um resultado muito perto de x, se x for um valor pequeno (isto é, porque eles são chamados logaritmos 'naturais'). Se você calcular Math.log(1 + 1.1111111111e-15) você obterá uma resposta perto de1.1111111111e-15. Ao invés, você vai acabar obtendo o logaritmo de 1.00000000000000111022 (o arrendondamento é feito em binário, portanto, as vezes isso pode parecer estranho), então você obterá o resultado 1.11022...e-15, com somente 3 digitos corretos. Se, ao invés, você calcular  Math.log1p(1.1111111111e-15) você terá um retorno mais preciso de 1.1111111110999995e-15 com 15 digitos corretos de precisão (na verdade 16 nesse caso).

+ +

Se o valor de x for menor que -1, o valor retornado será sempre {{jsxref("NaN")}}.

+ +

Por conta do log1p() ser um metódo estático de Math, você sempre chamará como Math.log1p(), ao invés de chamar como um método de um objeto Math que você tenha criado (Math não é um construtor).

+ +

Exemplos

+ +

Usando Math.log1p()

+ +
Math.log1p(1);  // 0.6931471805599453
+Math.log1p(0);  // 0
+Math.log1p(-1); // -Infinity
+Math.log1p(-2); // NaN
+
+ +

Polyfill

+ +

Isto pode ser implementado com a seguinte função:

+ +
Math.log1p = Math.log1p || function(x) {
+  return Math.log(1 + x);
+};
+
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('ES2015', '#sec-math.log1p', 'Math.log1p')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-math.log1p', 'Math.log1p')}}{{Spec2('ESDraft')}}
+ +

Compatibilidade com os navegadores

+ + + +

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

+ +

Veja também

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

A função Math.log2() retorna o logaritmo de base 2 de um número, que é

+ +

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

+ +

Sintaxe

+ +
Math.log2(x)
+ +

Parâmetros

+ +
+
x Um número.
+
+ +

Retorno

+ +

O logaritmo de base 2 de um número. Caso o número seja negativo, {{jsxref("NaN")}} é retornado.

+ +

Descrição

+ +

Caso o valor de x seja menor que 0, então o retorno será sempre {{jsxref("NaN")}}.

+ +

Por log2() ser um método estático de Math, você sempre o usará como Math.log2(), ao invés de usá-lo como método de um objeto  Math criado (Math não é um construtor).

+ +

Esta função é equivalente a Math.log(x)/Math.log(2).  Para log2(e) use a constante {{jsxref("Math.LOG2E")}} que é 1 / {{jsxref("Math.LN2")}}.  

+ +

Exemplos

+ +

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

+ +

Este Polyfill simula a função Math.log2. Note que é retornado um valor não prcesiso Observe que é retornado valores imprecisos em algumas entradas (like 1 << 29), envolva em {{jsxref("Math.round()")}} se estiver trabalhando com máscaras de bits.

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

Especificações

+ + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('ES2015', '#sec-math.log2', 'Math.log2')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-math.log2', 'Math.log2')}}{{Spec2('ESDraft')}} 
+ +

Compatibilidade de navegadores

+ + + +

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

+ +

Veja também

+ + diff --git a/files/pt-br/web/javascript/reference/global_objects/math/log2e/index.html b/files/pt-br/web/javascript/reference/global_objects/math/log2e/index.html new file mode 100644 index 0000000000..26669a3b45 --- /dev/null +++ b/files/pt-br/web/javascript/reference/global_objects/math/log2e/index.html @@ -0,0 +1,82 @@ +--- +title: Math.LOG2E +slug: Web/JavaScript/Reference/Global_Objects/Math/LOG2E +tags: + - JavaScript + - Math + - Property + - Propriedade + - Reference + - Referência(2) +translation_of: Web/JavaScript/Reference/Global_Objects/Math/LOG2E +--- +
{{JSRef}}
+ +

A propriedade Math.LOG2E representa o logaritmo com base 2 de e, aproximadamente 1.442:

+ +

Math.LOG2E=log2(e)1.442\mathtt{\mi{Math.LOG2E}} = \log_2(e) \approx 1.442

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

Descrição

+ +

Por LOG2E ser uma propriedade estática de Math, deve-se sempre usá-la como Math.LOG2E, e não como propriedade de um objeto Math criado por você (Math não é um construtor).

+ +

Exemplos

+ +

Usando Math.LOG2E

+ +

A função a seguir retorna o logaritmo com base 2 de e:

+ +
function getLog2e() {
+  return Math.LOG2E;
+}
+
+getLog2e(); // 1.4426950408889634
+
+ +

Especificações

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

Compatibilidade nos navegadores

+ + + +

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

+ +

Veja também

+ + diff --git a/files/pt-br/web/javascript/reference/global_objects/math/max/index.html b/files/pt-br/web/javascript/reference/global_objects/math/max/index.html new file mode 100644 index 0000000000..d59b1fb583 --- /dev/null +++ b/files/pt-br/web/javascript/reference/global_objects/math/max/index.html @@ -0,0 +1,155 @@ +--- +title: Math.max() +slug: Web/JavaScript/Reference/Global_Objects/Math/max +tags: + - JavaScript + - Math + - Method +translation_of: Web/JavaScript/Reference/Global_Objects/Math/max +--- +
{{JSRef("Global_Objects", "Math")}}
+ +

Sumário

+ +

A função Math.max() retorna o maior de um ou mais números.

+ +

Sintaxe

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

Parâmetros

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

Valor de retorno

+ +

O maior dos números passados como argumentos. Se pelo menos um dos argumentos não puder ser convertido para um número {{jsxref("NaN")}} é retornado.

+ +

Descrição

+ +

Por max ser um método estático em Math, você sempre irá usá-lo da seguinte maneira Math.max(), e não como um método da classe Math que você tenha instanciado.

+ +

Se nenhum argumento for passado o resultado sempre será - {{jsxref("Global_Objects/Infinity", "Infinity")}}.

+ +

Se um dos argumentos não puder ser convertido em um número, o resultado será {{jsxref("Global_Objects/NaN", "NaN")}}.

+ +

Exemplos

+ +

Usando Math.max

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

Retornando o maior elemento de um array

+ +

{{jsxref("Array.prototype.reduce", "Array.reduce()")}} pode ser usada para encontrar o maior elemento em um vetor numérico, comparando cada valor:

+ +
var arr = [1, 2, 3];
+var max = arr.reduce(function(a, b) {
+  return Math.max(a, b);
+});
+ +

A função a seguir utiliza {{jsxref("Function.prototype.apply()")}} para encontrar o elemento de maior valor dentro do array. getMaxOfArray([1,2,3]) é equivalente a Math.max(1, 2, 3), mas você pode usar getMaxOfArray  em arrays construídos programaticamente e o ideal é utilizá-la somente em arrays com relativamente poucos elementos.

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

O novo operador spread é um modo curto de se escrever a solução com apply para retornar o maior valor de um array.

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

Entretanto, tanto spread(...) quanto apply irão ou falhar ou retornar o resultado errado caso o array tenha muitos elementos, porque eles tentam passar o array de elementos como parâmetros de funções. Veja usando apply e funções embutidas para mais detalhes. A solução com reduce não apresenta esse problema.

+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
ECMAScript 1st Edition. Implemented in JavaScript 1.0StandardInitial definition.
{{SpecName('ES6', '#sec-15.8.2.11', 'Math.max')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math.max', 'Math.max')}}{{Spec2('ES6')}} 
+ +

Compatibilidade de Navegadores

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/javascript/reference/global_objects/math/min/index.html b/files/pt-br/web/javascript/reference/global_objects/math/min/index.html new file mode 100644 index 0000000000..ee97e97ddf --- /dev/null +++ b/files/pt-br/web/javascript/reference/global_objects/math/min/index.html @@ -0,0 +1,147 @@ +--- +title: Math.min() +slug: Web/JavaScript/Reference/Global_Objects/Math/min +translation_of: Web/JavaScript/Reference/Global_Objects/Math/min +--- +
+

{{JSRef}}

+ +

A função Math.min()  retorna o menor valor passado como parâmetro, ou {{jsxref("NaN")}}  se o parâmetro não é ou não pode ser convertido para um número.

+ +

Syntax

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

Parâmetros

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

Descrição

+ +

Por que  min() é um método estático de Math, você sempre usa como Math.min(),  e não como um método de um objeto Math que você criou (Math não é um construtor).

+ +

Se nenhum argumento for dado, o resultado é {{jsxref("Infinity")}}.

+ +

Se pelo menos um dos argumentos não pode ser convertido para um número, o resultado é {{jsxref("NaN")}}.

+ +

Exemplos

+ +

Usando Math.min()

+ +

Este encontra o min de x e y e atribui a z :

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

Cortando um valor com Math.min()

+ +

Math.min() é muitas vezes usado para cortar um valor sempre menor do que ou igual a um limite. Por exemplo, este.

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

pode ser escrita como este

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

{{jsxref("Math.max()")}} pode ser usado de uma maneira semelhante ao corte de um valor na outra extremidade.

+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoEstatoComentário
{{SpecName('ES1')}}{{Spec2('ES1')}}definição inicial. Implementado no 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')}} 
+ +

Compatibilidade do navegador 

+ +

{{CompatibilityTable}}

+ + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
+

Suporte

+ +

básico

+
{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+ + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+ +

Veja Também

+ + +
diff --git a/files/pt-br/web/javascript/reference/global_objects/math/pi/index.html b/files/pt-br/web/javascript/reference/global_objects/math/pi/index.html new file mode 100644 index 0000000000..22d97c22e9 --- /dev/null +++ b/files/pt-br/web/javascript/reference/global_objects/math/pi/index.html @@ -0,0 +1,82 @@ +--- +title: Math.PI +slug: Web/JavaScript/Reference/Global_Objects/Math/PI +tags: + - JavaScript + - Math + - PI + - Propriedade +translation_of: Web/JavaScript/Reference/Global_Objects/Math/PI +--- +
{{JSRef}}
+ +

A propriedade Math.PI representa a proporção entre circunferência de um círculo com o seu diâmetro, aproximadamente 3.14159:

+ +

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

+ +

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

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

Descrição

+ +

Como PI é uma propriedade estática de Math, sempre use-a como Math.PI, ao invés de uma propriedade de um objeto Math que você criou (Math não é um construtor).

+ +

Exemplos

+ +

Usando Math.PI

+ +

A seguinte função usa Math.PI para calcular a circunferência de um círculo com um dado raio.

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

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Definiçao inicial. Implementado no 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')}} 
+ +

Compatibilidade de navegadores

+ + + +

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

+ +

Veja também

+ + diff --git a/files/pt-br/web/javascript/reference/global_objects/math/pow/index.html b/files/pt-br/web/javascript/reference/global_objects/math/pow/index.html new file mode 100644 index 0000000000..0a478feb5a --- /dev/null +++ b/files/pt-br/web/javascript/reference/global_objects/math/pow/index.html @@ -0,0 +1,147 @@ +--- +title: Math.pow() +slug: Web/JavaScript/Reference/Global_Objects/Math/pow +tags: + - Função + - JavaScript + - Método(2) + - Referência(2) + - expoente + - potência +translation_of: Web/JavaScript/Reference/Global_Objects/Math/pow +--- +
{{JSRef}}
+ +

A função Math.pow() retorna a base elevada ao expoente power, ou seja, baseexpoente.

+ +

Sintaxe

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

Parâmetros

+ +
+
base
+
O número da base.
+
expoente
+
O expoente usado para elevar a base.
+
+ +

Descrição

+ +

Como pow() é um método estático de Math, você sempre irá usá-lo como Math.pow(), ao invés de usá-lo como um método de um objeto do tipo Math que você tenha criado (Math não é um construtor).

+ +

Exemplos

+ +

Usando Math.pow()

+ +
// simples
+Math.pow(7, 2);    // 49
+Math.pow(7, 3);    // 343
+Math.pow(2, 10);   // 1024
+// expoentes fracionários
+Math.pow(4, 0.5);  // 2 (raiz quadrada de 4)
+Math.pow(8, 1/3);  // 2 (raiz cúbica de 8)
+Math.pow(2, 0.5);  // 1.4142135623730951 (raiz quadrada de 2)
+Math.pow(2, 1/3);  // 1.2599210498948732 (raiz cúbica de 2)
+// expoentes com sinais
+Math.pow(7, -2);   // 0.02040816326530612 == (1/7)2 == (1/49)
+Math.pow(8, -1/3); // 0.5 == (1/8)1/3 == 1/2
+// bases com sinal
+Math.pow(-7, 2);   // 49 (quadrados sempre são positivos)
+Math.pow(-7, 3);   // -343 (cubos podem ser negativos conforme a base)
+Math.pow(-7, 0.5); // NaN (números negativos não tem uma raiz quadrada real)
+// devido ao fato que raízes "par" e "ímpar" são próximas,
+// e limitam a precisão de ponto flutuante,
+// bases negativas com expoentes fracionários sempre retornam NaN
+Math.pow(-7, 1/3); // NaN
+
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('ES1')}}{{Spec2('ES1')}}Definição Inicial. Implementado no 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')}} 
+ +

Compatibilidade com Navegadores

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FuncionalidadeChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte Básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FuncionalidadeAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte Básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/javascript/reference/global_objects/math/random/index.html b/files/pt-br/web/javascript/reference/global_objects/math/random/index.html new file mode 100644 index 0000000000..c3133554a8 --- /dev/null +++ b/files/pt-br/web/javascript/reference/global_objects/math/random/index.html @@ -0,0 +1,102 @@ +--- +title: Math.random() +slug: Web/JavaScript/Reference/Global_Objects/Math/random +tags: + - JavaScript + - Math + - Method + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Math/random +--- +
{{JSRef("Global_Objects", "Math")}}
+ +

Sumário

+ +

A função Math.random() retorna um número pseudo-aleatório no intervalo [0, 1[, ou seja, de 0 (inclusivo) até, mas não incluindo, 1 (exclusivo), que depois você pode dimensionar para um intervalo desejado.  A implementação seleciona uma semente para o algoritmo de geração de números aleatórios; esta semente não pode ser escolhida ou reatribuída.

+ +
+

Math.random() não gera números criptograficamente seguros. Não a use para nada relacionado a segurança. Use a API Web Crypto, mais precisamente o método {{domxref("RandomSource.getRandomValues()", "window.crypto.getRandomValues()")}}.

+
+ +

Sintaxe

+ +
Math.random()
+ +

Valor retornado

+ +

Um número pseudo-aleatório entre 0 (inclusivo) e 1 (exclusivo).

+ +

Exemplos

+ +

Note que os números em JavaScript são pontos flutuantes que seguem o padrão IEEE 754 com comportamento arredondar-para-o-par-mais-próximo, os intervalos que serão citados nos exemplos a seguir (exceto o exemplo do Math.random()), não são exatas. Se limites extremamente grandes forem escolhidos (253 ou maior), em raros casos é possível que o limite superior (que seria exclusivo) seja retornado.

+ +

Gerando um número aleatório entre 0 (inclusivo) e 1 (exclusivo)

+ +
function getRandom() {
+  return Math.random();
+}
+ +

Gerando um número aleatório entre dois valores

+ +

Este exemplo retorna um número entre dois valores definidos. O valor retornado será maior ou igual a min, e menor que max.

+ +
function getRandomArbitrary(min, max) {
+  return Math.random() * (max - min) + min;
+}
+ +

Gerando um número inteiro aleatório entre dois valores

+ +

Este exemplo retorna um número inteiro entre dois valores definidos. O valor não poderá ser menor que min (ou do próximo inteiro maior que min, caso min não seja inteiro), e será menor (mas não igual) a max.

+ +
function getRandomInt(min, max) {
+  min = Math.ceil(min);
+  max = Math.floor(max);
+  return Math.floor(Math.random() * (max - min)) + min;
+}
+ +

+ +
+

Pode ser tentandor usar Math.round() para arredondar min e max, mas dessa maneira a aleatoriedade dos números seguiria uma distribuição não-uniforme, que talvez não seja o que você precisa.

+
+ +

Gerando um número inteiro aleatório entre dois valores, inclusive

+ +

A função getRandomInt() acima tem intervalo com o valor mínimo incluído e o máximo excluído. Mas se você precisar que a função inclua, tanto o mínimo quanto o máximo, em seus resultados? A função getRandomIntInclusive() abaixo faz isso.

+ +
function getRandomIntInclusive(min, max) {
+  min = Math.ceil(min);
+  max = Math.floor(max);
+  return Math.floor(Math.random() * (max - min + 1)) + min;
+}
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('ES1')}}{{Spec2('ES1')}}Definição inicial. JavaScript 1.0 (UNIX Only) / JavaScript 1.1 (Todas plataformas).
{{SpecName('ES5.1', '#sec-15.8.2.14', 'Math.random')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math.random', 'Math.random')}}{{Spec2('ES6')}} 
+ +

Compatibilidade nos navegadores

+ +

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

diff --git a/files/pt-br/web/javascript/reference/global_objects/math/round/index.html b/files/pt-br/web/javascript/reference/global_objects/math/round/index.html new file mode 100644 index 0000000000..5473ab29aa --- /dev/null +++ b/files/pt-br/web/javascript/reference/global_objects/math/round/index.html @@ -0,0 +1,234 @@ +--- +title: Math.round() +slug: Web/JavaScript/Reference/Global_Objects/Math/round +tags: + - JavaScript + - Math + - Method +translation_of: Web/JavaScript/Reference/Global_Objects/Math/round +--- +
{{JSRef("Global_Objects", "Math")}}
+ +

Resumo

+ +

A função Math.round() retorna o valor de um número arredondado para o inteiro mais proximo.

+ +

Sintaxe

+ +
 Math.round(x) 
+ +

Parâmetros

+ +
+
x
+
Um número.
+
+ +

Retorno

+ +

O valor de um número dado aproximado para o inteiro mais próximo

+ +

Descrição

+ +

Se a parte fracionária do número for maior ou igual a  0.5, o argumento x é arredondado para o próximo número inteiro acima, entretanto se a parte fracionária do número for menor que 0.5, então o valor de x é arredondado para o próximo número inteiro abaixo. Se a parte fracionária for exatamente igual a 0.5, o número é arredondado para o próximo inteiro na direção de +∞.

+ +

Por round ser um método estático de Math, você sempre irá usá-lo como Math.round(), ao invés de usá-lo como um método da instância do objeto Math que você criou.

+ +

Exemplos

+ +

Exemplo: Uso de  Math.round

+ +
// Retorna o valor 20
+x = Math.round(20.49);
+
+// Retorna o valor 21
+x = Math.round(20.5);
+
+// Retorna o valor -20
+x = Math.round(-20.5);
+
+// Retorna o valor -21
+x = Math.round(-20.51);
+
+// Retorna 1 (!)
+// Note o erro de arredondamento por causa da inacurácia de aritmética de ponto flutuante
+// Compare o exemplo abaixo com Math.round10(1.005, -2)
+x = Math.round(1.005*100)/100;
+
+ +

Exemplo: Arredondamento decimal.

+ +
// Closure
+(function(){
+
+	/**
+	 * Ajuste decimal de um número.
+	 *
+	 * @param	{String}	type	O tipo de arredondamento.
+	 * @param	{Number}	value	O número a arredondar.
+	 * @param	{Integer}	exp		O expoente (o logaritmo decimal da base pretendida).
+	 * @returns	{Number}			O valor depois de ajustado.
+	 */
+	function decimalAdjust(type, value, exp) {
+		// Se exp é indefinido ou zero...
+		if (typeof exp === 'undefined' || +exp === 0) {
+			return Math[type](value);
+		}
+		value = +value;
+		exp = +exp;
+		// Se o valor não é um número ou o exp não é inteiro...
+		if (isNaN(value) || !(typeof exp === 'number' && exp % 1 === 0)) {
+			return NaN;
+		}
+		// Transformando para string
+		value = value.toString().split('e');
+		value = Math[type](+(value[0] + 'e' + (value[1] ? (+value[1] - exp) : -exp)));
+		// Transformando de volta
+		value = value.toString().split('e');
+		return +(value[0] + 'e' + (value[1] ? (+value[1] + exp) : exp));
+	}
+
+	// Arredondamento decimal
+	if (!Math.round10) {
+		Math.round10 = function(value, exp) {
+			return decimalAdjust('round', value, exp);
+		};
+	}
+	// Decimal arredondado para baixo
+	if (!Math.floor10) {
+		Math.floor10 = function(value, exp) {
+			return decimalAdjust('floor', value, exp);
+		};
+	}
+	// Decimal arredondado para cima
+	if (!Math.ceil10) {
+		Math.ceil10 = function(value, exp) {
+			return decimalAdjust('ceil', value, exp);
+		};
+	}
+
+})();
+
+// Round (arredondamento)
+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 este resultado com Math.round(1.005*100)/100 no exemplo acima
+// Floor (para baixo)
+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 (para cima)
+Math.ceil10(55.51, -1); // 55.6
+Math.ceil10(51, 1); // 60
+Math.ceil10(-55.59, -1); // -55.5
+Math.ceil10(-59, 1); // -50
+
+ +

Método de arredondamento PHP

+ +

O código abaixo pode ser utilizado para adicionar sua própria versão do Math.round ao seu namespace no qual tenha um parâmetro de precisão. Diferentemente do arredondamento decimal do exemplo acima, esse método não realiza conversão de e para strings, e o parâmetro de precisão funciona da mesma maneira que PHP e Excel onde um positivo 1 seria arredondado para 1 casa decimal e -1 seria arredondado para os decimais.

+ +
var myNamespace = {};
+
+myNamespace.round = function(number, precision) {
+    var factor = Math.pow(10, precision);
+    var tempNumber = number * factor;
+    var roundedTempNumber = Math.round(tempNumber);
+    return roundedTempNumber / factor;
+};
+
+myNamespace.round(1234.5678, 1); // 1234.6
+myNamespace.round(1234.5678, -1); // 1230
+
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
ECMAScript 1ª Edição. Implementado em JavaScript 1.0.PadrãoDefinição inicial.
{{SpecName('ES5.1', '#sec-15.8.2.15', 'Math.round')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-math.round', 'Math.round')}}{{Spec2('ES6')}}
+ +

Compatibilidade de Browser

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/javascript/reference/global_objects/math/sign/index.html b/files/pt-br/web/javascript/reference/global_objects/math/sign/index.html new file mode 100644 index 0000000000..03f8eed812 --- /dev/null +++ b/files/pt-br/web/javascript/reference/global_objects/math/sign/index.html @@ -0,0 +1,117 @@ +--- +title: Math.sign() +slug: Web/JavaScript/Reference/Global_Objects/Math/sign +translation_of: Web/JavaScript/Reference/Global_Objects/Math/sign +--- +
{{JSRef}}
+ +

A função Math.sign() retorna o sinal de um número, indicando se o número é positivo, negativo ou zero.

+ +

Sintaxe

+ +
Math.sign(x)
+ +

Parâmetros

+ +
+
x
+
Se o parametro passado ao for numerico, a função irá converter o parametro em Um número.
+
+ +

Valor retornado

+ +

Um número representando o sinal do argumento fornecido.

+ +

Se o argumento é um número positivo, o retorno será 1;

+ +

Se o numero passado for negativo, o retorno será -1

+ +

Se o argumento for um zero positivo , o retorno será +0

+ +

Se o argumento for 0 negativo , o retorno será -0

+ +

. Qualquer outro valor que não seja numérico (string transformada em numero por ex.), o retorno será {{jsxref("NaN")}} 

+ +

Descrição

+ +

Pela razão de sign() ser um método estático de Math, você sempre deve usá-lo como Math.sign(), e não como um método do objeto Math que você criou (Math não é um construtor).

+ +

Esta função possui 5 tipos de valores retornados, 1, -1, 0, -0, NaN, que representam "número positivo", "número negativo", "zero positivo", "zero negativo" e {{jsxref("NaN")}}, respectivamente.

+ +

O argumento passado para esta função será implicitamente convertido para o tipo numérico.

+ +

Exemplos

+ +

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) {
+    // Se x é NaN, o resultado é NaN.
+    // Se x é -0, o resultado é -0.
+    // Se x é +0, o resultado é +0.
+    // Se x é negativo e não -0, o resultado é -1.
+    // Se x é positivo e não +0, o resultado é +1.
+    return ((x > 0) - (x < 0)) || +x;
+    // Uma representação mais estética é mostrada abaixo
+    //
+    // ( (x > 0) ? 1 : 0 )  // se x é positivo então mais um
+    //          +           // senão (porque não poder ser - e +)
+    // ( (x < 0) ? -1 : 0 ) // se x é negativo então menos um
+    //         ||           // se x é 0, -0, NaN, ou não é um número,
+    //         +x           // Então o resultado será x, (ou) se x não é
+    //                      // um número, então converte x para número
+  };
+}
+
+ +

No polyfill acima, nenhuma coerção de tipo extra é necessária para tornar numéricos as expressões (x > 0) ou (x < 0) , porque subtraindo-as um do outro força uma conversão de tipo de booleano para numérico.

+ +

Especificações

+ + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('ES6', '#sec-math.sign', 'Math.sign')}}{{Spec2('ES6')}}Definição inicial.
{{SpecName('ESDraft', '#sec-math.sign', 'Math.sign')}}{{Spec2('ESDraft')}}
+ +

Compatibilidade com navegadores

+ + + +

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

+ +

Veja também

+ + diff --git a/files/pt-br/web/javascript/reference/global_objects/math/sin/index.html b/files/pt-br/web/javascript/reference/global_objects/math/sin/index.html new file mode 100644 index 0000000000..3e5cdea187 --- /dev/null +++ b/files/pt-br/web/javascript/reference/global_objects/math/sin/index.html @@ -0,0 +1,92 @@ +--- +title: Math.sin() +slug: Web/JavaScript/Reference/Global_Objects/Math/sin +translation_of: Web/JavaScript/Reference/Global_Objects/Math/sin +--- +
{{JSRef}}
+ +

A função Math.sin() retorna o seno de um número.

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

Sintaxe

+ +
Math.sin(x)
+ +

Paramêtros

+ +
+
x
+
Um número (dado em radianos)
+
+ +

Valor retornado

+ +

O seno de um número dado.

+ +

Descrição

+ +

O método Math.sin() retorna um valor numérico entre -1 e 1, que representa o seno de um angulo dado em radianos.

+ +

Como sin() é um método estático de Math, você sempre o usa como Math.sin(), ao invés de um método de um objeto Math que você criou (Math não é um construtor).

+ +

Exemplos

+ +

Usando Math.sin()

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

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Definição inicial. Implementado no 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')}} 
{{SpecName('ESDraft', '#sec-math.sin', 'Math.sin')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ + + +

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

+ +

Veja também

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

A função Math.sinh() retorna o seno hiperbólico de um número, que pode ser expresso usando a {{jsxref("Math.E", "constante e", "", 1)}}:

+ +

Math.sinh(x)=ex-e-x2\mathtt{\operatorname{Math.sinh(x)}} = \frac{e^x - e^{-x}}{2}

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

Sintáxe

+ +
Math.sinh(x)
+ +

Parâmetros

+ +
+
x
+
Um número.
+
+ +

Valor retornado

+ +

O seno hiperbólico do número dado.

+ +

Descrição

+ +

Como sinh() é um método estático de Math, você sempre deve usar como Math.sinh(), ao invés de um novo objeto instanciado Math (Math não é um construtor).

+ +

Exemplos

+ +

Usando Math.sinh()

+ +
Math.sinh(0); // 0
+Math.sinh(1); // 1.1752011936438014
+
+ +

Polyfill

+ +

Isso pode ser emulado com a ajuda da função {{jsxref("Math.exp()")}}:

+ +
Math.sinh = Math.sinh || function(x) {
+  return (Math.exp(x) - Math.exp(-x)) / 2;
+}
+
+ +

ou usando apenas uma chamada para a função {{jsxref("Math.exp()")}}:

+ +
Math.sinh = Math.sinh || function(x) {
+  var y = Math.exp(x);
+  return (y - 1 / y) / 2;
+}
+
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('ES2015', '#sec-math.sinh', 'Math.sinh')}}{{Spec2('ES2015')}}Definição inicial.
{{SpecName('ESDraft', '#sec-math.sinh', 'Math.sinh')}}{{Spec2('ESDraft')}} 
+ +

Compatibilidade nos navegadores

+ + + +

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

+ +

Veja também

+ + diff --git a/files/pt-br/web/javascript/reference/global_objects/math/sqrt/index.html b/files/pt-br/web/javascript/reference/global_objects/math/sqrt/index.html new file mode 100644 index 0000000000..17c9f65bb4 --- /dev/null +++ b/files/pt-br/web/javascript/reference/global_objects/math/sqrt/index.html @@ -0,0 +1,87 @@ +--- +title: Math.sqrt() +slug: Web/JavaScript/Reference/Global_Objects/Math/sqrt +tags: + - JavaScript + - Math + - Method + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Math/sqrt +--- +
{{JSRef("Global_Objects", "Math")}}
+ +

Resumo

+ +

A função Math.sqrt() retorna a raiz quadrada de um número (x\sqrt{x}) .

+ +

Sintaxe

+ +
Math.sqrt(x) 
+ +

Parâmetros

+ +
+
x
+
Um número.
+
+ +

Valor retornado

+ +

A raiz quadrada do número recebido. Se o número for negativo, a função retornará {{jsxref("NaN")}}.

+ +

Descrição

+ +

Se o valor de x for negativo, Math.sqrt() retorna {{jsxref("NaN")}}.

+ +

Por sqrt ser um método estático de Math, deve-se sempre usá-lo como Math.sqrt(), e não como um método de um objeto Math que você criou.

+ +

Exemplos

+ +

Exemplo: Usando Math.sqrt

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

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('ES1')}}{{Spec2('ES1')}}Definição inicial. Implementado no 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')}} 
+ +

Compatibilidade nos navegadores

+ +

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

+ +

Ver também

+ + diff --git a/files/pt-br/web/javascript/reference/global_objects/math/sqrt1_2/index.html b/files/pt-br/web/javascript/reference/global_objects/math/sqrt1_2/index.html new file mode 100644 index 0000000000..5c2aa35e4a --- /dev/null +++ b/files/pt-br/web/javascript/reference/global_objects/math/sqrt1_2/index.html @@ -0,0 +1,81 @@ +--- +title: Math.SQRT1_2 +slug: Web/JavaScript/Reference/Global_Objects/Math/SQRT1_2 +tags: + - JavaScript + - Math + - Property + - Propriedade + - Reference + - Referencia +translation_of: Web/JavaScript/Reference/Global_Objects/Math/SQRT1_2 +--- +
{{JSRef}}
+ +

A propriedade Math.SQRT1_2 representa a raiz quadrada de 12\frac{1}{2}, que é aproximadamente 0.707:

+ +

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

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

Descrição

+ +

Por SQRT1_2 ser um método estático de Math, deve-se sempre usá-lo como Math.SQRT1_2(), e não como um método de um objeto Math que você criou.

+ +

Exemplos

+ +

Usando Math.SQRT1_2

+ +

A função a seguir retorna 1 sobre a raiz quadrada de 2:

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

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in 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')}} 
+ +

Compatibilidade nos navegadores

+ + + +

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

+ +

Veja também

+ + diff --git a/files/pt-br/web/javascript/reference/global_objects/math/sqrt2/index.html b/files/pt-br/web/javascript/reference/global_objects/math/sqrt2/index.html new file mode 100644 index 0000000000..7c8ceeaa5d --- /dev/null +++ b/files/pt-br/web/javascript/reference/global_objects/math/sqrt2/index.html @@ -0,0 +1,81 @@ +--- +title: Math.SQRT2 +slug: Web/JavaScript/Reference/Global_Objects/Math/SQRT2 +tags: + - JavaScript + - Math + - Property + - Propriedade + - Reference + - Referência(2) +translation_of: Web/JavaScript/Reference/Global_Objects/Math/SQRT2 +--- +
{{JSRef}}
+ +

A propriedade Math.SQRT2 representa a raiz quadrada de 2, que é aproximadamente 1.414:

+ +

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

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

Descrição

+ +

Por SQRT2 ser uma propriedade estática de Math, deve-se sempre usá-la como Math.SQRT2, e não como propriedade de um objeto Math criado por você (Math não é um construtor).

+ +

Examples

+ +

Usando Math.SQRT2

+ +

A função a seguir retorna a raiz quadrada de 2:

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

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in 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')}} 
+ +

Compatibilidade nos navegadores

+ + + +

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

+ +

Veja também

+ + diff --git a/files/pt-br/web/javascript/reference/global_objects/math/tan/index.html b/files/pt-br/web/javascript/reference/global_objects/math/tan/index.html new file mode 100644 index 0000000000..0b0897490a --- /dev/null +++ b/files/pt-br/web/javascript/reference/global_objects/math/tan/index.html @@ -0,0 +1,111 @@ +--- +title: Math.tan() +slug: Web/JavaScript/Reference/Global_Objects/Math/tan +tags: + - JavaScript + - Matemática + - metodo +translation_of: Web/JavaScript/Reference/Global_Objects/Math/tan +--- +
+ {{JSRef("Global_Objects", "Math")}}
+

Resumo

+

A função Math.tan() retorna a tangente de um número.

+

Sintaxe

+
Math.tan(x)
+

Parâmetros

+
+
+ x
+
+ Um número representando um ângulo em radianos.
+
+

Descrição

+

O método tan retorna um valor numérico que representa a tangente do ângulo.

+

Como tan é um método estático de Math, use sempre Math.tan(), ao invés de um método de um objeto Math que você tenha criado.

+

Exemplos

+

Exemplo: Usando Math.tan

+

A seguinte função retorna a tangente da variável x:

+
function getTan(x) {
+   return Math.tan(x);
+}
+

Como a função Math.tan() trabalha com radianos, mas normalment epe mais fácil trabalhar em graus, a seguinte função aceita um valor em graus, converte-o para radianos e retorna a tangente.

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

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
ECMAScript 1st Edition. Implementado em JavaScript 1.0PadrãoDefinição inicial.
{{SpecName('ES5.1', '#sec-15.8.2.18', 'Math.tan')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math.tan', 'Math.tan')}}{{Spec2('ES6')}} 
+

Compatibilidade de navegadores

+

{{ CompatibilityTable() }}

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

 

diff --git a/files/pt-br/web/javascript/reference/global_objects/math/tanh/index.html b/files/pt-br/web/javascript/reference/global_objects/math/tanh/index.html new file mode 100644 index 0000000000..1122f98d69 --- /dev/null +++ b/files/pt-br/web/javascript/reference/global_objects/math/tanh/index.html @@ -0,0 +1,88 @@ +--- +title: Math.tanh() +slug: Web/JavaScript/Reference/Global_Objects/Math/tanh +translation_of: Web/JavaScript/Reference/Global_Objects/Math/tanh +--- +
{{JSRef}}
+ +

A função Math.tanh()  retorna a tangente hiperbólica de um número, que é:

+ +

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")}}
+ +

Syntax

+ +
Math.tanh(x)
+ +

Parameters

+ +
+
x
+
Um número.
+
+ +

Return value

+ +

Uma tangente hiperbólica de um número dado.

+ +

Description

+ +

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

+ +

Examples

+ +

Using Math.tanh()

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

Polyfill

+ +

This can be emulated with the help of the {{jsxref("Math.exp()")}} function:

+ +
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);
+}
+
+ +

Specifications

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

Browser compatibility

+ + + +

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

+ +

See also

+ + diff --git a/files/pt-br/web/javascript/reference/global_objects/math/trunc/index.html b/files/pt-br/web/javascript/reference/global_objects/math/trunc/index.html new file mode 100644 index 0000000000..cba3259de7 --- /dev/null +++ b/files/pt-br/web/javascript/reference/global_objects/math/trunc/index.html @@ -0,0 +1,144 @@ +--- +title: Math.trunc() +slug: Web/JavaScript/Reference/Global_Objects/Math/trunc +tags: + - Math + - Trunc +translation_of: Web/JavaScript/Reference/Global_Objects/Math/trunc +--- +
{{JSRef}}
+ +

O método Math.trunc() retorna a parte inteira de um número, descartando suas casas decimais.

+ +

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

+ +

Sintaxe

+ +
Math.trunc(x)
+ +

Parâmetros

+ +
+
x
+
Um número.
+
+ +

 

+ +

Valor de retorno

+ +

A parte inteira de um dado número.

+ +

 

+ +

Descrição

+ +

Diferente dos demais métodos em Math: {{jsxref("Math.floor()")}}, {{jsxref("Math.ceil()")}} e {{jsxref("Math.round()")}}, o retorno esperado da função Math.trunc() é simples e direto, ela apenas trunca o número passado a ela como parâmetro, removendo todas as casas decimais dele, não importando se o número é positivo ou negativo.

+ +

Portanto, se o argumento passado for um número positivo, Math.trunc() será equivalente a Math.floor(), caso contrário Math.trunc() será equivalente a Math.ceil().

+ +

O argumento passado a esse método será convertido a um tipo numérico implicitamente.

+ +

Já que trunc() é um método estático em Math, sempre utilize Math.trunc(), ao invés de um método existente no objeto que você criou (Math não é um construtor).

+ +

Exemplos

+ +

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

+ +

(umPolyfill é um pedaço de código que o desenvolvedor pode colocar na sua página para garantir compatilibilidade do método. No exemplo abaixo, caso o navegador não tiver o método trunc na classe Math, ele será criado);

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

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('ES6', '#sec-math.trunc', 'Math.trunc')}}{{Spec2('ES6')}}Definição inicial.
+ + + +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome("38")}}{{CompatGeckoDesktop("25")}}{{CompatNo}}{{CompatOpera("25")}}{{CompatSafari("7.1")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile("25")}}{{CompatNo}}{{CompatNo}}8
+
+ +

Veja também

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