본문 바로가기

Language & Framework/Java

자바 Math 클래스의 기본 활용

 

 

Math 클래스의 생성자는 접근 제어자가 private으로 설정되어 있기 때문에 인스턴스 생성이 불가능하며, 모든 메서드가 static으로 정의되어 있다.

또한 Math 클래스에는 두 가지의 상수가 있는데 그것은 PI(원주율)와 E(자연로그의 밑)다.

System.out.println("Math.PI = " + Math.PI);
System.out.println("Math.E = " + Math.E);

//Math.PI = 3.141592653589793
//Math.E = 2.718281828459045

 

아무래도 Math 클래스에서 가장 많이 사용되는 메서드는 Random과 foor, round, ceil일 것이다.

일단 가장 먼저 round를 활용한 소수점 n자리까지 반올림하는 방법을 알아보자.

 

double num = 12.987156;
num = Math.round(num*100);
num = num / 100.0;
System.out.println("Math.round(num*100)/100 = " + num);

// Math.round(num*100)/100 = 12.99

 

round()메서드는 소수점 첫째 자리에서 반올림하거나 버림으로 int를 반환한다.

따라서 소수점 둘째 자리까지 반올림한 결과를 얻고 싶다면 100을 곱한 뒤 round 메서드로 반올림(혹은 버림)처리하고 다시 100으로 나누면 된다.

중요한 것은 Math.round()메서드를 사용하면 double이나 float이 아닌 int로 타입이 변환되기 때문에 나눌 때 100이 아닌 100.0으로 나누어야 한다는 것이다.

 

System.out.println(" 기준값 = " + num);
System.out.println("Math.ceil(num) = " + Math.ceil(num)); // 올림
System.out.println("Math.floor(num+0.99) = " + Math.floor(num)); // 내림
System.out.println("Math.rint(num+0.99) = " + Math.rint(num)); // 반올림
System.out.println("Math.round(num+0.99) = " + Math.round(num)); // 반올리거나 버림(반환값 int)

//기준값 = 12.99
//Math.ceil(num) = 13.0
//Math.floor(num+0.99) = 12.0
//Math.rint(num+0.99) = 13.0
//Math.round(num+0.99) = 13

 

Math.ceil은 올림, Math.floor는 내림, Math.rint는 반올림, Math.round는 버리거나 반올림이다.

Math.round()만 유일하게 int를 반환하고 있는 것을 확인할 수 있다.

 

int x = 30000;
int y = 20000;
long longNum = 100000000L;
System.out.println("기준값 x = " + x + ", y = " + y);
System.out.println("addExact(x,y) = " + addExact(x,y));
System.out.println("subtractExact(x,y) = " + subtractExact(x,y));
System.out.println("multiplyExact(x,y) = " + multiplyExact(x,y));
System.out.println("incrementExact(x) = " + incrementExact(x));
System.out.println("decrementExact(x) = " + decrementExact(x));
System.out.println("negateExact(x) = " + negateExact(x));
System.out.println("toIntExact(longNum) = " + toIntExact(longNum));
//기준값 x = 30000, y = 20000
//addExact(x,y) = 50000
//subtractExact(x,y) = 10000
//multiplyExact(x,y) = 600000000
//incrementExact(x) = 30001
//decrementExact(x) = 29999
//negateExact(x) = -30000
//toIntExact(longNum) = 100000000

 

Math 클래스에는 위와 같이 Exact가 포함된 산술 연산 메서드들이 있다.

이 메서드의 특징은 정수형 연산에서 발생하는 OverFlow를 체크해서 ArithmeticException 예외를 발생시킨다.

 

System.out.println("Math.pow(100.0, 2) = " + Math.pow(100.0, 2));
System.out.println("Math.pow(100.0, 0.5) = " + Math.pow(100.0, 0.5));
System.out.println("Math.sqrt = " + Math.sqrt(100));
//Math.pow(100.0, 2) = 10000.0
//Math.pow(100.0, 0.5) = 10.0
//Math.sqrt = 10.0

 

위의 pow와 sqrt는 각각 제곱, 제곱근을 구해주는 메서드이다.

다만 pow의 두번째 파라미터에 소수값을 넣으면 제곱근을 구할 수 있어서 (ex ) Math.pow(100.0, 0.5)는 100.0의 제곱근을 구한다 ) 굳이 sqrt가 필요한지는 모르겠다.

지금까지 배운 것들을 응용해서 삼각함수를 계산할 수 있다.. 솔직히 말하자면 다 잊어버려서 유튜브에서 중등 수학 강의 보고 왔다 ^^..

 

내가 이걸 15년 지나서 다시 볼 줄이야.. ^^~~~

int x1 = 10;
int y1 = 10;
int x2 = 20;
int y2 = 20;
double c = sqrt((Math.pow(x2-x1,2)) + (Math.pow(y2-y1,2)));
System.out.println("좌표 (10, 10), (20, 20)간의 거리 = " + c);

double a = c * sin(PI/4);
double b = c * cos(PI/4);
double d = toDegrees(atan2(a,b));
System.out.printf("a의 길이는 %f이고 b의 길이는 %f이다. 그리고 끼인 각은 %f도이다.%n", a,b,c);
//좌표 (10, 10), (20, 20)간의 거리 = 14.142135623730951
//a의 길이는 10.000000이고 b의 길이는 10.000000이다. 그리고 끼인 각은 45.000000도이다.

위 공식을 자바에 옮기면 이렇게 된다.

잘 이해가 되지 않는다면 자바 공부를 잠깐 멈추고 유튜브에 중등 수학 강의를 보러 가자.

내가 이런 걸 배웠었나 싶을 것이다.

 

System.out.println("24자리의 2진수는 10진수로 몇 자리인가? log10(2) * 24 ? " + (log10(2) * 24));
System.out.println("53자리의 2진수는 10진수로 몇 자리인가? log10(2) * 53 ? " + (log10(2) * 53));

상용 로그를 사용해 2진수를 10진수로 몇 자리의 값인지 계산할 수 있다.

직접 계산하는 것은 노가다지만 계산기를 이용하면 편리하다.

 

 

int x1 = 10;
int x2 = 20;
System.out.println("Math.max(x1, x2) = " + Math.max(x1, x2));
System.out.println("Math.min(x1, x2) = " + Math.min(x1, x2));
System.out.println("Math.abs(-10000) = " + Math.abs(-10000));
System.out.println("Math.random() = " + Math.random());

//Math.max(x1, x2) = 20 큰 수 반환
//Math.min(x1, x2) = 10 작은 수 반환
//Math.abs(-10000) = 10000 절대값 구하기
//Math.random() = 0.38907671457100457 1.0을 제외한 0~1.0 무작위 반환

 

마지막으로 자주 쓰이는 메서드들이다.