CS/Algorithm

[Java] Math 클래스

칸타탓 2019. 4. 15. 15:47

Math 정리

 

기본 수학적 함수들을 제공하는 클래스이다. 대부분 실수형(double)을 반환함에 주의

 

- abs

절대값 반환 (int 반환)

Math.abs(-4) //4

 

- ceil

올림 수 반환

Math.ceil(55.5) //56.0
Math.ceil(55.3) //56.0

 

- floor

소수점 버림

Math.floor(55.5) //55.0
Math.floor(55.3) //55.0

 

- round

반올림값 반환

Math.round(55.5) //56.0

 

- exp(x)

승 된 값을 반환(x를 인수로 하는 e^x 값을 반환)

 

- pow(x, y)

누승한 값을 반환, x의 y승

 

- sqrt(x)

x의 제곱근, 루트

 

- min(x, y)

작은 수 반환

- static int min(int a , int b)

- static double min(double a , double b)

- static float min(float a , float b)

- static long min(long a , long b)

 

- max(x, y)

큰 수 반환

- static int max(int a , int b)

- static double max(double a , double b)

- static float max(float a , float b)

- static long max(long a , long b)

 

- signum(x)

부호 반환, 양수면 +1, 음수면 -1

 

- rint(x)

정수부 반환.

rint(-123.4567) = -123.0

 

- log(x)

밑이 e(2.718...)인 자연로그 함수

 

- log10(x)

밑이 10인 로그 함수

Math.log10(10) //1.0

 

- random

현재 시간을 seed로 사용한 난수 반환 (max는 곱하고, min 값은 추가로 더해준다)

public class RandomExample {
    public static void main(String[] args)  {
        System.out.println("0.0 ~ 1.0 사이의 난수 1개 발생 : " + Math.random());));
        System.out.println("1 ~ 100 사이의 난수 1개 발생 : " + (int)(Math.random() * 100) + 1);
        System.out.println("min ≤ x ≤ max : " + (int) (Math.random() * (max - min + 1) + min));
    }
}

- 랜덤수를 생성하는 다른 방법

import java.util.Random;

public class RandomExample {
	public static void main(String[] args)  {
        Random random = new Random(); // 랜덤 객체 생성(디폴트 시드값 : 현재시간)
        random.setSeed(System.currentTimeMillis()); // 시드값 설정을 따로 할 수도 있음

        System.out.println("0이상 10(n)이하의 무작위 정수값 : " + random.nextInt(10)); 
        System.out.println("무작위 boolean 값 : " + random.nextBoolean());
        System.out.println("무작위 long 값 : " + random.nextLong());
        System.out.println("무작위 float 값 : " + random.nextFloat());
        System.out.println("무작위 double 값 : " + random.nextDouble());
        System.out.println("무작위 정규 분포의 난수 값 :" + random.nextGaussian());
    }
}