자바스크립트
Section 6. 자바스크립트 Math 객체
포칼이
2023. 3. 31. 11:08
Math 객체는 수학에 관련된 기능을 가진 빌트인 객체이다.
특성은 다음과 같다.
- 정적 프로퍼티와 메서드만 제공한다.
- Number 타입만 지원한다. -BigInt 사용이 불가능하다.
I. 주요 정적 프로퍼티
PI - 원주율
console.log(
Math.PI
); //3.141592653589793
E - 자연로그의 밑
console.log(
Math.E
); //2.718281828459045
II. 주요 정적 메서드
1. abs - 절대값(0 이상) 반환
console.log(
Math.abs(123),
Math.abs(-123),
); //123 123
0을 반환하는 경우이다.
// 0 반환
console.log(
Math.abs(0),
Math.abs(''),
Math.abs(null),
Math.abs([]),
); //0 0 0 0
NaN을 반환하는 경우이다.
// NaN 반환
console.log(
Math.abs('abc'),
Math.abs(undefined),
Math.abs({a: 1}),
Math.abs([1, 2, 3]),
Math.abs()
); //NaN NaN NaN NaN NaN
const isEqual = (a, b) => {
return Math.abs(a - b) < Number.EPSILON;
}
console.log(
isEqual(0.1 + 0.2, 0.3)
); //true
2. ceil, round, floor, trunc
각각 올림, 반올림, 내림, 정수부만 반환한다 라는 의미하는 메서드들이다.
for (const num of [1.4, 1.6, -1.4, -1.6]) {
console.log(
num + ' : ',
Math.ceil(num), //1.4 : 2 1 1 1
Math.round(num), //1.6 : 2 2 1 1
Math.floor(num), //-1.4 : -1 -1 -2 -1
Math.trunc(num), //-1.6 : -1 -2 -2 -1
);
}
빈 값을 넣었을때는 다음과 같다.
console.log(
Math.ceil(),
Math.round(),
Math.floor(),
Math.trunc()
); //NaN NaN NaN NaN
3. pow - ~로 거듭제곱
console.log(
Math.pow(4, 2), // 4 ** 2
Math.pow(4, 1), // 4 ** 1
Math.pow(4, 0), // 4 ** 0
Math.pow(4, -1) // 4 ** -1
); //16 4 1 0.25
** 연산자를 쓰면 더 간결하게 표현이 가능하다.
// NaN 반환
console.log(
Math.pow(4)
); //NaN
인자에 두 숫자가 필요한 것을 볼 수 있다. 아니면 NaN을 반환한다.
4. sqrt - 제곱근
console.log(
Math.sqrt(25), // 25 ** 0.5
Math.sqrt(9),
Math.sqrt(2),
Math.sqrt(1),
Math.sqrt(0)
); //5 3 1.4142135623730951 1 0
NaN을 반환하는 경우는 다음과 같다.
console.log(
Math.sqrt(-25),
Math.sqrt()
); //NaN NaN
5. max, min - 인자들 중 최대값과 최소값
console.log(
Math.max(8, 5, 9, 6, 3, 1, 4, 2, 7),
Math.min(8, 5, 9, 6, 3, 1, 4, 2, 7)
); //9 1
6. random - 0~1 사이의 무작위 값
for (let i = 0; i < 10; i++) {
console.log(Math.random());
} //0.16681809033535844 등등
0~1사이의 무작위 숫자들이 (0.16681809033535844 이렇게 나온다) 출력된다.
정수를 출력하고 싶다면 다음과 같이 하면 된다.
for (let i = 0; i < 10; i++) {
console.log(
Math.floor(Math.random() * 10)
);
}
그러면 0~9사이의 정수가 무작위로 출력된다.
*이 방법은 안전한 난수 생성은 아니다.
보안에 관련된 것이라면 전용 라이브러리 또는 아래 링크의 방식을 쓸 것을 권장한다.
링크 : https://developer.mozilla.org/ko/docs/Web/API/Crypto/getRandomValues
7. sin, cos, tan, asin, acos, atan
각각 사인, 코사인, 탄젠트, 아크사인, 아크코사인, 아크탄젠트를 의미하는 메서드들이다.
console.log(
// 1(또는 근사값) 반환
Math.sin(Math.PI / 2),
Math.cos(Math.PI * 2),
Math.tan(Math.PI / 180 * 45)
); //1 1 0.9999999999999999
console.log(
// Math.PI / 2 반환
Math.asin(1),
Math.acos(0),
Math.atan(Infinity)
); //1.5707963267948966 1.5707963267948966 1.5707963267948966