JAVA

자바의 Math

D_Helloper 2023. 5. 29. 15:11

java.lang.Math 클래스

  • 수학에서 자주 사용하는 상수들과 함수들을 미리 구현해 놓은 클래스
  • 모든 메소드는 static method이므로, 객체를 생성하지 않고 바로 사용 가능

Math.E와 Math.PI

  • Math.E : 오일러의 수, 자연 로그의 밑 값으로 약 2.718을 의미
  • Math.PI : 원의 원주를 지름으로 나눈 비율(원주율) 값, 약 3.14159를 의미

random() 메소드

  • 0.0 이상 1.0 미만의 범위에서 임의의 double형 값을 하나 생성하여 반환
  • 내부적으로 java.util 패키지의 Random 클래스를 사용한 의사 난수 발생기(pseudorandom-number generator)를 사용하여 임의의 수 생성
  • 아래 코드는 0부터 99까지의 난수를 생성하는 예
System.out.println((int)(Math.random() * 100)); // 0 ~ 99
Random ran = new Random();
System.out.println(ran.nextInt(100));           // 0 ~ 99

기타 유용한 Math 메소드들의 사용법

System.out.println(Math.round(3.14));  // 반올림
System.out.println(Math.ceil(3.14));   // 올림
System.out.println(Math.floor(3.14));  // 내림
System.out.println(Math.pow(3, 2));    // 지수승
System.out.println(Math.sqrt(9));      // 제곱근
System.out.println(Math.abs(-10));     // 절댓값

// 0 <= Math.random() < 1 
// 2~8 사이 랜덤 수 만들기
System.out.println((int)Math.random()*7+2 );     // 랜덤값 

System.out.println(Math.max(10, 5)); // 최댓값
System.out.println(Math.min(10, 5)); // 최솟값