Skip to content

mathx

Since v8.0.75

arrange()

등차수열 형태의 숫자 배열을 생성합니다.

사용 형식
arrange(start, end, step)
매개변수
  • start Number 시작값
  • end Number 종료값
  • step Number 증가 폭
반환값

Array<Number> 생성된 숫자 배열.

사용 예시
1
2
3
4
5
6
const { arrange } = require('mathx');
arrange(0, 6, 3).forEach((i) => console.log(i));

// 0
// 3
// 6

linspace()

지정한 구간을 균등 간격으로 분할한 배열을 생성합니다.

사용 형식
linspace(start, end, count)
매개변수
  • start Number 시작값
  • end Number 종료값
  • count Number 생성할 요소 개수
반환값

Array<Number> 생성된 숫자 배열.

사용 예시
1
2
3
4
5
6
const { linspace } = require('mathx');
linspace(0, 1, 3).forEach((i) => console.log(i));

// 0
// 0.5
// 1

meshgrid()

두 배열의 조합을 기반으로 격자를 생성합니다.

사용 형식
meshgrid(arr1, arr2)
매개변수
  • arr1 Array<Number> 첫 번째 배열
  • arr2 Array<Number> 두 번째 배열
반환값

``Array<Array>` 숫자 쌍으로 구성된 배열.

사용 예시
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
const { meshgrid } = require('mathx');

const gen = meshgrid([1, 2, 3], [4, 5]);
for(i=0; i < gen.length; i++) {
    console.log(JSON.stringify(gen[i]));
}

// [1,4]
// [1,5]
// [2,4]
// [2,5]
// [3,4]
// [3,5]

oscillator()

Since v8.5.5

[time, value] 튜플 형태의 진동 샘플 데이터를 생성합니다.

사용 형식
oscillator(options)
매개변수
  • options Object
  • options.components Object[] 필수. 합성할 진동 성분 목록
    • amplitude Number 필수. 진폭
    • frequencyHz Number 필수. 주파수(Hz)
    • phaseRad Number 선택. 위상 오프셋(라디안), 기본값 0
    • bias Number 선택. DC 오프셋, 기본값 0
  • options.timeRange Object 필수. 시간 범위
    • from Any 필수
    • to Any 필수
    • 지원 시간 표현:
      • 숫자 epoch ns (예: 0, 10000000000)
      • 접미사 epoch 문자열: s, ms, us, ns (예: "10s", "10000ms")
      • 문자열 시간 표현: "now", "now-10s"
      • RFC3339/RFC3339Nano 문자열
  • options.sample Number|String 선택
    • 숫자: 샘플 개수로 해석
    • Hz/hz 접미사 문자열: 샘플링 주파수로 해석 (예: "2Hz")
  • options.noise Number|Object 선택
    • 숫자: 노이즈 진폭으로 해석
    • 객체: { amplitude, seed? } 형식이며 amplitude는 노이즈 세기, seed는 재현 가능한 노이즈를 위한 시드입니다.
반환값

Array<[time, Number]> 생성된 샘플 배열.

사용 예시
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
const { oscillator } = require('mathx');

const gen = oscillator({
        components: [
                { amplitude: 1.0, frequencyHz: 0.1, phaseRad: 0 },
                { amplitude: 0.5, frequencyHz: 0.05 },
        ],
        timeRange: { from: '0s', to: '10s' },
        sample: '2Hz',
        noise: { amplitude: 0.1, seed: 123 },
});

for (let i = 0; i < gen.length; i++) {
        const t = gen[i][0];
        const v = gen[i][1];
        console.log(t, v.toFixed(2));
}

series()

Since v8.5.5

[time, value] 튜플 샘플 배열을 시간 배열과 값 배열로 분리합니다.

사용 형식
series(samples, options)
매개변수
  • samples Array<[time, Number]> 튜플 샘플 배열
  • options Object 선택
    • xKey String x축 배열 키 이름, 기본값 "time"
    • yKey String y축 배열 키 이름, 기본값 "value"
반환값

두 개의 배열을 담은 Object를 반환합니다. 기본 형태는 { time, value }입니다.

사용 예시
const m = require("mathx");
const gen = m.oscillator({
    components: [{ amplitude: 1.0, frequencyHz: 0.1 }],
    timeRange: { from: "0s", to: "10s" },
    sample: 5,
});

const s = m.series(gen);
console.log(s.time.length);  // 5
console.log(s.value.length); // 5

const custom = m.series(gen, { xKey: "ts", yKey: "amp" });
console.log(custom.ts.length);  // 5
console.log(custom.amp.length); // 5

unzip()

Since v8.5.5

튜플 샘플 배열을 두 개의 배열로 분리합니다.

사용 형식
unzip(samples)
매개변수
  • samples Array<[x, y]> 튜플 샘플 배열
반환값

[Array<x>, Array<y>]

사용 예시
const m = require("mathx");
const [x, y] = m.unzip([[1, 10], [2, 20], [3, 30]]);
console.log(x); // [1, 2, 3]
console.log(y); // [10, 20, 30]

zip()

Since v8.5.5

두 개의 배열을 튜플 샘플 배열로 합칩니다.

사용 형식
zip(x, y)
매개변수
  • x Array<any> x축 데이터 배열
  • y Array<any> y축 데이터 배열 (x와 길이가 같아야 함)
반환값

Array<[x, y]>

사용 예시
const m = require("mathx");
const samples = m.zip([1, 2, 3], [10, 20, 30]);
console.log(samples[0]); // [1, 10]

fft()

고속 푸리에 변환(FFT)을 수행하여 주파수 성분을 분석합니다.

입력은 두 가지 형식을 지원하며, 결과는 [frequency, amplitude] 형태의 배열로 반환됩니다.

사용 형식
fft(times, amplitudes) // 시간 배열과 진폭 배열
fft(timesAndAmplitudes) // [time, amplitude] 배열
  • fft(times, amplitudes) timesamplitudes를 각각 별도의 배열로 전달합니다.
  • fft(timesAndAmplitudes) [time, amplitude] 쌍으로 이루어진 배열을 전달합니다.

timesamplitudes를 별도 배열로 전달하는 경우, 두 배열의 길이는 반드시 같아야 합니다.

반환 값

Array<[frequency, amplitude]> 주파수와 진폭 쌍의 배열.

사용 예시

const m = require("mathx");
const gen = m.oscillator({
    components: [
        {amplitude: 1.0, frequencyHz: 15},
        {amplitude: 1.5, frequencyHz: 24},
    ],
    timeRange: {from: 'now', to: 'now+10s'},
    sample: "1000Hz",
});
// gen is array of tuple (time, amplitude)
// ffp() accepts array of (time, amplitude) 
// and returns array of (frequency, amplitude)
const result = m.fft(gen);
for(i=0; i < result.length; i++) {
    console.println(i, result[i][0], result[i][1]);
}

sort()

배열을 오름차순으로 정렬합니다.

사용 예시

1
2
const m = require('mathx');
console.log(m.sort([1.3, 1.2, 1.1])); // [1.1, 1.2, 1.3]

sum()

배열의 합계를 계산합니다.

사용 예시

1
2
3
const m = require('mathx');
console.log(m.sum([3, 1, 2]));       // 6
console.log(m.sum([1.3, 1.2, 1.1])); // 3.6

cdf()

누적 분포 함수(CDF)를 계산합니다. 주어진 x 데이터에서 q 이하인 비율을 반환합니다.

사용 형식
cdf(q, x, weights)
  • q Number 기준 값
  • x Array<Number> 오름차순으로 정렬된 데이터
  • weights Array<Number> 가중치 배열(생략 시 모두 1, 지정 시 x와 길이가 같아야 합니다.)

사용 예시

1
2
3
4
5
6
7
const m = require('mathx');
x = [];
for( i=1; i<=100; i++) {
    x.push(i);
}
x = m.sort(x);
console.log(m.cdf(1.0, x)); // 0.01

mean()

산술 평균을 계산합니다.

사용 예시

1
2
3
const m = require('mathx');
console.log(m.mean([1, 2, 3, 4, 5]));  // 3
console.log(m.mean([10, 20, 30]));     // 20

circularMean()

라디안 각도와 같이 순환하는 값을 대상으로 평균을 구합니다. 가중치 배열을 지정할 수도 있습니다.

사용 예시

1
2
3
4
5
const m = require('mathx');
x = [0, 0.25 * Math.PI, 0.75 * Math.PI];
w = [1, 2, 2.5];
console.log(m.circularMean(x).toFixed(4));     // 0.9553
console.log(m.circularMean(x, w).toFixed(4));  // 1.3704

correlation()

두 데이터셋 간 피어슨 상관 계수를 계산합니다. -1~1 범위이며 가중치를 지정할 수도 있습니다.

사용 예시

1
2
3
4
5
6
const m = require('mathx');
x = [8, -3, 7, 8, -4];
y = [10, 5, 6, 3, -1];
w = [2, 1.5, 3, 3, 2];
console.log(m.correlation(x, y).toFixed(5));     // 0.61922
console.log(m.correlation(x, y, w).toFixed(5));  // 0.59915

covariance()

두 데이터셋 간 공분산을 계산합니다. 양수면 함께 증가하는 경향, 음수면 반대로 움직이는 경향을 의미합니다.

사용 예시

1
2
3
4
5
6
7
const m = require('mathx');
x = [8, -3, 7, 8, -4];
y1 = [10, 2, 2, 4, 1];
y2 = [12, 1, 11, 12, 0];
console.log(m.covariance(x, y1).toFixed(4)); // 13.8000
console.log(m.covariance(x, y2).toFixed(4)); // 37.7000
console.log(m.variance(x).toFixed(4));       // 37.7000

entropy()

샤논 엔트로피를 계산해 분포의 불확실성을 측정합니다.

사용 예시

1
2
3
4
5
const m = require('mathx');
console.log(m.entropy([0.05, 0.1, 0.9, 0.05]).toFixed(4)); // 0.6247
console.log(m.entropy([0.2, 0.4, 0.25, 0.15]).toFixed(4)); // 1.3195
console.log(m.entropy([0.2, 0, 0, 0.5, 0, 0.2, 0.1, 0, 0, 0]).toFixed(4)); // 1.2206
console.log(m.entropy([0, 0, 1, 0]).toFixed(4));           // 0.0000

geometricMean()

양수 배열의 기하 평균을 계산합니다.

사용 예시

1
2
3
const m = require('mathx');
console.log(m.geometricMean([1, 3, 9]).toFixed(4));  // 3.0000
console.log(m.geometricMean([2, 8, 32]).toFixed(4)); // 8.0000

harmonicMean()

양수 배열의 조화 평균을 계산합니다.

사용 예시

1
2
3
const m = require('mathx');
console.log(m.harmonicMean([1, 2, 4]).toFixed(4));    // 1.7143
console.log(m.harmonicMean([10, 20, 30]).toFixed(4)); // 16.3636

median()

정렬된 배열의 중앙값을 반환합니다. 짝수 개라면 두 중앙값의 평균을 돌려줍니다.

입력 배열은 오름차순으로 정렬되어 있어야 합니다.

사용 예시

1
2
3
const m = require('mathx');
console.log(m.median(m.sort([1, 3, 2, 5, 4])));      // 3
console.log(m.median(m.sort([10, 20, 30, 40, 50]))); // 30

medianInterp()

median과 동일하지만, 선형 보간을 적용한 값을 반환합니다.

사용 예시

1
2
3
const m = require('mathx');
console.log(m.medianInterp(m.sort([1, 3, 2, 5, 4])));      // 2.5
console.log(m.medianInterp(m.sort([10, 20, 30, 40, 50]))); // 25

quantile()

The quantile function calculates the quantile of a given dataset for a specified probability. Quantiles divide the dataset into intervals with equal probabilities, such as quartiles (4 intervals) or percentiles (100 intervals). This function is useful for understanding the distribution of data.

사용 형식
quantile(p, x, weights)
  • p Number
  • x Array<Number> The x data must be sorted in increasing order.
  • weights Array<Number> If weights is not specified then all of the weights are 1. If weights is specified, then length of x must equal length of weights.

사용 예시

1
2
3
4
5
const m = require('mathx');
data = m.sort([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
console.log(m.quantile(0.25, data)); // 3
console.log(m.quantile(0.5, data));  // 5
console.log(m.quantile(0.74, data)); // 8

quantileInterp()

quantile과 동일하지만 선형 보간 값을 반환합니다.

사용 형식
quantileInterp(p, x, weights)
  • p Number 백분위 비율
  • x Array<Number> 정렬된 데이터
  • weights Array<Number> 가중치 배열(선택)

사용 예시

1
2
3
4
5
const m = require('mathx');
data = m.sort([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
console.log(m.quantileInterp(0.25, data)); // 2.5
console.log(m.quantileInterp(0.5, data));  // 5
console.log(m.quantileInterp(0.74, data)); // 7.4

meanStdDev()

평균과 표준편차를 동시에 계산합니다.

사용 예시

1
2
3
4
5
const m = require('mathx');
data = [1, 2, 3, 4, 5];
result = m.meanStdDev(data);
console.log(result.mean.toFixed(2));   // 3.00
console.log(result.stdDev.toFixed(2)); // 1.58

mode()

최빈값을 계산합니다. 결과는 {value: number, count: number} 형태입니다.

사용 형식
mode(x, weights)
  • x Array<Number> 정렬된 데이터
  • weights Array<Number> 가중치 배열(선택)

사용 예시

1
2
3
4
5
const m = require('mathx');
data = m.sort([1, 2, 2, 3, 4]);
console.log(m.mode(data)); // {value:2, count:2}
data = m.sort([1, 1, 2, 3, 4]);
console.log(m.mode(data)); // {value:1, count:2}

moment()

n차 모멘트를 계산합니다. 분포 형태(왜도·첨도 등)를 분석할 때 사용합니다.

사용 예시

1
2
3
4
const m = require('mathx');
data = [1, 2, 3, 4, 5];
console.log(m.moment(2, data).toFixed(4)); // 2.5000
console.log(m.moment(4, data).toFixed(4)); // 6.8000

stdDev()

표준편차를 계산합니다.

사용 예시

1
2
3
const m = require('mathx');
console.log(m.stdDev([1, 2, 3, 4, 5]).toFixed(4));      // 1.5811
console.log(m.stdDev([10, 20, 30, 40, 50]).toFixed(4)); // 15.8114

stdErr()

표본 평균의 표준 오차를 계산합니다. 표준편차를 표본 크기의 제곱근으로 나눈 값입니다.

사용 예시

1
2
3
4
const m = require('mathx');
let stddev = m.stdDev([1, 2, 3, 4, 5]);
let sampleSize = 5;
console.log(m.stdErr(stddev, sampleSize).toFixed(4)); // 0.7071

linearRegression()

두 데이터셋을 대상으로 선형 회귀를 수행합니다. 결과는 y = alpha*x + beta 형태의 {slope: alpha, intercept: beta}입니다.

사용 예시

1
2
3
4
5
6
const m = require('mathx');
x = [1, 2, 3, 4, 5];
y = [2, 4, 6, 8, 10];
result = m.linearRegression(x, y);
console.log(result.slope.toFixed(4));     // 2.0000
console.log(result.intercept.toFixed(4)); // 0.0000
최근 업데이트