Matemáticas
Math
es uno de los objetos integrados estándar o globales de JavaScript, y se puede usar en cualquier lugar donde pueda usar JavaScript. Contiene constantes útiles como π y constante de Euler y las funciones tales como floor()
, round()
, y ceil()
.
En este artículo, veremos ejemplos de muchas de esas funciones. Pero primero, aprendamos más sobre el Math
objeto.
Ejemplo
El siguiente ejemplo muestra cómo usar el Math
objeto para escribir una función que calcula el área de un círculo:
function calculateCircleArea(radius) { return Math.PI * Math.pow(radius, 2); } calculateCircleArea(1); // 3.141592653589793
Matemáticas Max
Math.max()
es una función que devuelve el valor más grande de una lista de valores numéricos pasados como parámetros. Si se pasa un valor no numérico como parámetro, Math.max()
se devolverá NaN
.
Se puede pasar una matriz de valores numéricos como un único parámetro para Math.max()
usar spread (...)
o apply
. Sin embargo, cualquiera de estos métodos puede fallar cuando la cantidad de valores de matriz es demasiado alta.
Sintaxis
Math.max(value1, value2, value3, ...);
Parámetros
Números o matriz limitada de números.
Valor devuelto
El mayor de los valores numéricos dados, o NaN
si algún valor dado no es numérico.
Ejemplos
Números como parámetros
Math.max(4, 13, 27, 0, -5); // returns 27
Parametro invalido
Math.max(4, 13, 27, 'eight', -5); // returns NaN
Matriz como parámetro, usando Spread (…)
let numbers = [4, 13, 27, 0, -5]; Math.max(...numbers); // returns 27
Matriz como parámetro, usando Aplicar
let numbers = [4, 13, 27, 0, -5]; Math.max.apply(null, numbers); // returns 27
Math Min
La función Math.min () devuelve el menor de cero o más números.
Puede pasarle cualquier número de argumentos.
Math.min(7, 2, 9, -6); // returns -6
PI de matemáticas
Math.PI
es una propiedad estática del objeto Math y se define como la relación entre la circunferencia de un círculo y su diámetro. Pi es aproximadamente 3,14149 y, a menudo, se representa con la letra griega π.
Ejemplos
Math.PI \\ 3.141592653589793
Más información:
MDN
Math Pow
Math.pow()
devuelve el valor de un número a la potencia de otro número.
Sintaxis
Math.pow(base, exponent)
, donde base
es el número base y exponent
es el número por el cual aumentar el base
.
pow()
es un método estático de Math
, por lo tanto, siempre se llama como Math.pow()
método en otro objeto y no como método.
Ejemplos
Math.pow(5, 2); // 25 Math.pow(7, 4); // 2401 Math.pow(9, 0.5); // 3 Math.pow(-8, 2); // 64 Math.pow(-4, 3); // -64
Matemáticas Sqrt
La función Math.sqrt()
devuelve la raíz cuadrada de un número.
Si se ingresa un número negativo, NaN
se devuelve.
sqrt()
es un método estático de Math
, por lo tanto, siempre se llama como Math.sqrt()
método en otro objeto y no como método.
Sintaxis
Math.sqrt(x)
, donde x
es un número.
Ejemplos
Math.sqrt(25); // 5 Math.sqrt(169); // 13 Math.sqrt(3); // 1.732050807568 Math.sqrt(1); // 1 Math.sqrt(-5); // NaN
Trunc de matemáticas
Math.trunc()
es un método del objeto estándar matemático que devuelve solo la parte entera de un número dado simplemente eliminando unidades fraccionarias. Esto da como resultado un redondeo general hacia cero. Cualquier entrada que no sea un número dará como resultado una salida de NaN.
Careful: This method is an ECMAScript 2015 (ES6) feature and thus is not supported by older browsers.
Examples
Math.trunc(0.1) // 0 Math.trunc(1.3) // 1 Math.trunc(-0.9) // -0 Math.trunc(-1.5) // -1 Math.trunc('foo') // NaN
Math Ceil
The Math.ceil()
is a method of the Math standard object that rounds a given number upwards to the next integer. Take note that for negative numbers this means that the number will get rounded “towards 0” instead of the number of greater absolute value (see examples).
Examples
Math.ceil(0.1) // 1 Math.ceil(1.3) // 2 Math.ceil(-0.9) // -0 Math.ceil(-1.5) // -1
Math Floor
Math.floor()
is a method of the Math standard object that rounds a given number downwards to the next integer. Take note that for negative numbers this means that the number will get rounded “away from 0” instead of to the number of smaller absolute value since Math.floor()
returns the largest integer less than or equal to the given number.
Examples
Math.floor(0.9) // 0 Math.floor(1.3) // 1 Math.floor(0.5) // 0 Math.floor(-0.9) // -1 Math.floor(-1.3) // -2
An application of math.floor: How to Create a JavaScript Slot Machine
For this exercise, we have to generate three random numbers using a specific formula and not the general one. Math.floor(Math.random() * (3 - 1 + 1)) + 1;
slotOne = Math.floor(Math.random() * (3 - 1 + 1)) + 1; slotTwo = Math.floor(Math.random() * (3 - 1 + 1)) + 1; slotThree = Math.floor(Math.random() * (3 - 1 + 1)) + 1;
Another example: Finding the remainder
Example
5 % 2 = 1 because Math.floor(5 / 2) = 2 (Quotient) 2 * 2 = 4 5 - 4 = 1 (Remainder)
Usage
In mathematics, a number can be checked even or odd by checking the remainder of the division of the number by 2.
17 % 2 = 1 (17 is Odd) 48 % 2 = 0 (48 is Even)
Note Do not confuse it with modulus%
does not work well with negative numbers.
More math-related articles:
- Converting an am/pm clock to 24 hour time
- Simpson's rule
- What is a Hexagon?