본문 바로가기
Language/java

java.lang 패키지(Math 클래스)

by gamxong 2022. 7. 14.

Math 클래스

 

: Math클래스의 메서드는 모두 static이며, 2개의 상수만을 정의해 놓았다.

public static final double E = 2.7182818...;
public static final double PI = 3.141592...;

 

 

올림, 버림, 반올림

 

1. 원래 값에 100을 곱한다.
   90.7552 * 100 → 9075.52

2. 위의 결과에 Math.round()를 사용한다.
   Math.round(9075.52) → 9076

3. 위의 결과를 다시 100.0으로 나눈다.
   9076 / 100.0 → 90.76

 

rint() : round()처럼 소수점 첫째자리에서 반올림하지만, 반환값이 double이다. 또한, 음수일 때의 결과가 다르다.

          : 소수점 첫째자리가 5를 초과하는 값일 때만 반올림한다.

System.out.printf("round(%3.1f)=%d%n", 1.6, round(1.5); // 반환값이 int
System.out.printf("rint(%3.1f)=%f%n", 1.6, rint(1.5);   // 반환값이 double

System.out.printf("round(%3.1f)=%d%n", -1.5, round(-1.5));  // -1
System.out.printf("rint(%3.1f)=%f%n", -1.5, rint(-1.5);     // -2.0

 

 

예외를 발생시키는 메서드

 

 

- 연산자는 결과만을 반환할 뿐, 오버플로우가 발생했는지는 알려주지 않음.

- 아래의 메서드들은 오버플로우가 발생하면, 예외를 발생시킴.

 

int addExact(int x, int y)      // x+y
int subtractExact(int x, int y) // x-y
int multiplyExact(int x, int y) // x*y
int incrementExact(int a)       // a++
int decrementExact(int a)       // a--
int negateExact(int a)          // -a
int toIntExact(long value)      // (int)value - int로의 형변환

 

 

 

삼각함수와 지수, 로그

 

import static java.lang.Math.*;
import static java.lang.System.*;

class MathEx3 {
	public static void main(String args[]) {
        int x1=1, y1=1;
        int x2=2, y2=2;
        
        double c = sqrt(pow(x2-x1,2) + pow(y2-y1, 2));
        double a = c*sin(PI/4);
        double b = c*cos(PI/4);
       // double b = c*cos(toRadians(45));
       
       out.printf("a=%f%n",a);
       out.printf("b=%f%n",b);
       out.printf("c=%f%n",c);
       out.printf("angle=%f rad%n", atan2(a,b));
       
       out.printf("angle=%f degree %n", atan2(a,b)*180/PI);
       out.printf("24*log10(2)=%f%n", 24*log10(2));
       out.printf("53*log10(2)=%f%n", 53*log10(2));
       }
}

 

★ atan2 메서드 : 직각 삼각형에서 두 변의 길이 a,b를 알면 '끼인각'을 구해준다, 결과값은 라디안

- 라디안을 도(degree)단위로 변환 : '180/PI' 곱해주거나 toDegrees(double angrad) 이용

 

 

 

StrictMath클래스

: 성능은 다소 포기하는 대신, 어떤 OS에서 실행되어도 항상 같은 결과를 얻도록 Math클래스를 새로 작성한 것

 

 

 

Math클래스의 메서드

 

 

static double abs(double a) 절댓값 반환
static double ceil(double a) 올림하여 반환
static double floor(double a) 버림하여 반환
static double max(double a, double b) 큰 쪽을 반환
static double min(double a, double b) 작은 쪽을 반환
static double random() 0.0<= x < 1.0 범위의 임의의 double 값 반환
static double rint(double a) 주어진 double값과 가장 가까운 정수값을 double형으로 반환
static long round(double a) 반올림한 정수값(long)을 반환

 

 

 

댓글