Math.random() vs. new Random()

TIL·2022년 12월 10일
0

Java (최은빈)

목록 보기
9/27

Math.random() vs. Random

package me.day04.random;

import java.util.Random;

public class RandomExample {
    public static void main(String[] args) {
        // 컴퓨터에서 진짜 랜덤값은 없다. '수식'에 의해 생성된 '수식의 결과물'을 랜덤값으로 사용
        // seed * (수식) = 랜덤값 -> 바뀌는 seed(컴퓨터의 현재 시간)에 의해 랜덤값은 변함

        //// Math.random()
        // import 안해도 사용할 수 있는 java.lang 패키지 안의 Math 클래스
        // Random 클래스로 내부 구현함
        // seed = 컴퓨터 현재 시간 (변경 불가)

        // double 반환 : 0.0 <= Math.random() < 1.0
        // [1 ~ 100 사이의 정수 랜덤값 반환시키기]
        // 1. 0.0 <= Math.random() * 100 < 100.0
        // 2. 0 <= (int)(Math.random() * 100) < 100
        // 3. 1 <= (int)(Math.random() * 100) + 1 < 101
        int randomValue = (int)(Math.random() * 100) + 1;
        System.out.println(randomValue + " : 1 부터 100 사이의 랜덤값"); // 실행 시킬때마다 랜덤값 변경


        //// Random ramdomm = new Random();
        // import 해야 사용 가능한 클래스, 실무적으로 더 많이 사용
        // 암호화를 위한 난수 생성에서는 rsa, sha256, sha512 사용하여 복호화 어렵게함 (password encode)
        Random random = new Random();
        random.setSeed(3); // seed 값 설정 가능(기본값인 컴퓨터 현재 시간 무시). 동일 seed 가지면 동일한 랜덤값 생성됨

        // 수식 안만들고 메서드 사용
        int randomValue2 = random.nextInt(100) + 1;
        System.out.println(randomValue2 + " : 1 부터 100 사이의 랜덤값"); // 동일한 seed 이므로 랜덤값 고정

        // double, int, boolean, float, long, byte 반환 가능
        System.out.println( random.nextInt() );        // 1483266798 (int 표현범위 사이값)
        System.out.println( random.nextInt(10) );      // 1 (0 <= 값 < 10)
        System.out.println( random.nextInt(10) + 1 );  // 3 (1 <= 값 < 11)
        System.out.println( random.nextInt(10) * (-1) );  // -6 (-10 < 값 <= 0)
        System.out.println( random.nextBoolean() );    // false (true or false)
        System.out.println( random.nextLong() );       // -7488279853580653828 (long 표현범위 사이값)
        System.out.println( random.nextFloat() );      // 0 ~ 1 : 0.5873405 (float 표현범위 사이값)
        System.out.println( random.nextDouble() );		 // 0 ~ 1 : 0.4279275246744185 (더 넒은 유효범위)
    }
}

0개의 댓글

관련 채용 정보