프로그래밍 문제의 90%를 커버하는 다섯 가지 수학 연산
Source: Dev.to
수년간 도구를 만들고 코드를 검토하면서, 프로덕션 소프트웨어에서 사용되는 대부분의 수학 연산이 다섯 가지 범주로 귀결된다는 것을 발견했습니다. 수학 학위가 필요하지 않습니다. 이 다섯 영역에 능통하면 됩니다.
1. 백분율 계산
백분율은 어디에나 있습니다: 할인, 세금, 팁, 진행 바, 분석 대시보드, A/B 테스트 결과.
// What is X% of Y?
const percentOf = (percent, total) => (percent / 100) * total;
// What percentage is X of Y?
const whatPercent = (part, total) => (part / total) * 100;
// Percentage change from A to B
const percentChange = (oldVal, newVal) =>
((newVal - oldVal) / oldVal) * 100;백분율 변화 공식은 개발자들이 가장 자주 틀리는 것입니다. 분모는 이전 값이며, 새로운 값이 아닙니다. 50에서 75로 증가하는 것은 50 % 증가이며, 75에서 50으로 감소하는 것은 33.3 % 감소입니다. 비대칭성이 사람들을 혼란스럽게 합니다.
2. 선형 보간
값을 한 범위에서 다른 범위로 매핑합니다. 애니메이션, 데이터 시각화, 색상 그라디언트, 오디오 처리 및 센서 보정에 사용됩니다.
function lerp(value, inMin, inMax, outMin, outMax) {
return outMin + ((value - inMin) * (outMax - outMin)) / (inMax - inMin);
}
// Map a 0‑1023 sensor reading to 0‑100%
lerp(512, 0, 1023, 0, 100); // 50.05%
// Map a 0‑1 progress value to a 200‑800px width
lerp(0.75, 0, 1, 200, 800); // 650px역함수(값이 범위 내에서 어디에 해당하는지 찾는)는 동일하게 유용합니다:
function inverseLerp(value, min, max) {
return (value - min) / (max - min);
}
// Where does 650 fall in the 200‑800 range?
inverseLerp(650, 200, 800); // 0.753. 반올림 및 정밀도
JavaScript의 부동소수점 연산은 유명하게도 놀라운 결과를 만들어냅니다:
0.1 + 0.2 // 0.30000000000000004표시를 위한 실용적인 해결 방법:
function round(value, decimals) {
return Number(Math.round(value + 'e' + decimals) + 'e-' + decimals);
}
round(0.1 + 0.2, 2); // 0.3재무 계산에서는 절대 부동소수점을 사용하지 마세요. 정수 센트 단위를 사용합니다:
// Wrong
const price = 19.99;
const tax = price * 0.08; // 1.5992000000000002
// Right
const priceCents = 1999;
const taxCents = Math.round(priceCents * 0.08); // 160
const totalCents = priceCents + taxCents; // 2159
const totalDollars = (totalCents / 100).toFixed(2); // "21.59"4. 모듈러 연산
모듈로 연산자(%)는 배열을 순환하거나 값의 범위를 감싸는 데, 짝수/홀수 판별 및 시간 계산 등에 사용됩니다.
// Cycle through an array
const colors = ['red', 'green', 'blue'];
const color = colors[index % colors.length];
// Wrap a value within bounds
function wrap(value, min, max) {
const range = max - min;
return ((value - min) % range + range) % range + min;
}
// Convert seconds to hours:minutes:seconds
function formatTime(totalSeconds) {
const hours = Math.floor(totalSeconds / 3600);
const minutes = Math.floor((totalSeconds % 3600) / 60);
const seconds = totalSeconds % 60;
return `${hours}:${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;
}wrap에 사용된 이중 모듈로 연산은 음수를 처리합니다. JavaScript의 % 연산자는 음수 피제수에 대해 음수 결과를 반환하는데, 이는 보통 원하는 동작이 아닙니다.
5. 기본 통계
평균, 중앙값, 표준 편차는 모니터링, 알림, 데이터 분석 및 성능 측정에 사용됩니다.
const mean = arr => arr.reduce((a, b) => a + b, 0) / arr.length;
const median = arr => {
const sorted = [...arr].sort((a, b) => a - b);
const mid = Math.floor(sorted.length / 2);
return sorted.length % 2
? sorted[mid]
: (sorted[mid - 1] + sorted[mid]) / 2;
};
const stdDev = arr => {
const avg = mean(arr);
const variance = mean(arr.map(x => (x - avg) ** 2));
return Math.sqrt(variance);
};표준 편차는 데이터가 얼마나 퍼져 있는지를 알려줍니다. 모니터링에서 메트릭이 평균에서 2 표준 편차 이상 벗어나면 비정상적인 상황이 발생한 것입니다. 이는 대부분의 이상 탐지 시스템의 기반이 됩니다.
결합하기
실제 문제는 여러 작업을 결합합니다. “파일 업로드에 대한 진행률 막대를 퍼센트와 예상 남은 시간과 함께 표시하기”:
function uploadProgress(bytesUploaded, totalBytes, elapsedMs) {
const percent = whatPercent(bytesUploaded, totalBytes);
const rate = bytesUploaded / elapsedMs; // bytes per ms
const remaining = (totalBytes - bytesUploaded) / rate;
return {
percent: round(percent, 1),
barWidth: lerp(percent, 0, 100, 0, 300), // 300px bar
remainingSeconds: Math.ceil(remaining / 1000)
};
}어떤 수학 계산이든 단계별 해결 과정을 통해 진행하려면, 나는 .에 솔버를 두고 사용합니다. 기본 산술부터 대수와 통계까지 모든 것을 빠르고 무료로 처리하며, 풀이 과정을 보여줍니다.