본문 바로가기

Frontend/jQuery & JSTL

[jQuery] 백분위수 배열

반응형

 

function calculatePercentile(data, percentile) {
    // 데이터 배열을 정렬
    const sortedData = data.slice().sort((a, b) => a - b);

    // 백분위에 해당하는 인덱스 계산
    const index = (percentile / 100) * (sortedData.length - 1);

    // 정수 인덱스와 소수점 부분 분리
    const integerPart = Math.floor(index);
    const decimalPart = index - integerPart;

    // 백분위 값 계산
    let percentileValue;
    if (decimalPart === 0) {
        // 정확한 인덱스가 있는 경우
        percentileValue = sortedData[integerPart];
    } else {
        // 인덱스가 소수점인 경우
        percentileValue =
            (1 - decimalPart) * sortedData[integerPart] +
            decimalPart * sortedData[integerPart + 1];
    }

    // 최대값 및 최소값 계산
    const minValue = sortedData[0];
    const maxValue = sortedData[sortedData.length - 1];

    return {
        percentile: percentileValue,
        min: minValue,
        max: maxValue,
    };
}

// 예제 데이터 배열
const data = [15, 22, 34, 48, 50, 55, 65, 72, 80, 85];

// 75 백분위의 값, 최소값, 최대값 구하기
const result = calculatePercentile(data, 75);

console.log(`75 백분위의 값: ${result.percentile}`);
console.log(`최소값: ${result.min}`);
console.log(`최대값: ${result.max}`);

 

반응형