vanilladocs
vanillapunch.com
API / base/math

base/math

수학 보조 함수. (원본 base/math.js)

  • 수는 원본 자바스크립트 수처럼 f64 다. random_int 만 i32 다.
  • 원본의 floor, ceil, sqrt, abs, sin, cos, tan, asin, acos, pow 를 같은 이름의 함수로 둔다. (쓰는 코드가 원본과 같게) sin, cos, tan 은 원본처럼 크롬 Math.sin, cos, tan 과 같은 셈(바르게 반올림한 f64, base/trigonometry.rs)이다. (시스템 libm 은 플랫폼마다 끝자리가 다르다) round 는 반을 +무한대 쪽으로 올리는 점(-2.5 → -2)이 f64::round(-2.5 → -3)와 달라 원본 식 그대로 옮겼다.
  • 무작위는 엔진의 random(xorshift64*)을 쓴다. (원본 Math.random 자리)
  • 원본 shuffle 의 randomFunction 기본 인자는 shuffle(엔진 random), shuffle_with_random_function(넘긴 함수)으로 나눴다.

Math helper functions. (the original base/math.js)

  • Numbers are f64 like the original JavaScript numbers. Only random_int is i32.
  • The original floor, ceil, sqrt, abs, sin, cos, tan, asin, acos and pow are kept as functions of the same names. (so using code matches the original) sin, cos and tan compute what Chrome's Math.sin, cos and tan compute, as in the original (correctly rounded f64, base/trigonometry.rs). (the system libm has different last digits on each platform) round rounds halves toward +infinity (-2.5 → -2), which differs from f64::round (-2.5 → -3), so the original formula was ported as is.
  • Randomness uses the engine's random (xorshift64*). (in place of the original Math.random)
  • The default randomFunction argument of the original shuffle is split into shuffle (engine random) and shuffle_with_random_function (a passed function).
예제Example범위 제한, 보간, 반올림, 각 바꾸기, 난수Range clamping, interpolation, rounding, angle conversion, random numbers
use vanilla::math;

assert_eq!(math::clamp(15.0, 0.0, 10.0), 10.0);
assert_eq!(math::lerp(0.0, 10.0, 0.25), 2.5);
assert_eq!(math::round(-2.5), -2.0);
assert!((math::degree_to_radian(180.0) - math::PI).abs() < 1e-6);

let value = math::random_range(5.0, 10.0);
assert!(value >= 5.0 && value <= 10.0);

함수Functions

함수functionpub fn min(left: f64, right: f64) -> f64#0.4.0 부터since 0.4.0소스source

더 낮은 수. (원본처럼 left < right 가 아니면 right, NaN 이 끼면 f64::min 과 다르다)

The lower number. (right unless left < right, as in the original; differs from f64::min when NaN is involved)

leftf64
첫째 수.First number.
rightf64
둘째 수.Second number.

반환Returnsf64 left < right 면 left, 아니면 right. (어느 쪽이든 NaN 이면 right)left if left < right, otherwise right. (right if either is NaN)

짝Counterpart: vanilla.js min

예제ExampleNaN 이 끼면 둘째 값The second value when NaN is involved
use vanilla::math;

assert_eq!(math::min(2.0, 1.0), 1.0);
assert_eq!(math::min(f64::NAN, 1.0), 1.0);
assert!(math::min(1.0, f64::NAN).is_nan());
함수functionpub fn max(left: f64, right: f64) -> f64#0.4.0 부터since 0.4.0소스source

더 높은 수. (원본처럼 left > right 가 아니면 right)

The higher number. (right unless left > right, as in the original)

leftf64
첫째 수.First number.
rightf64
둘째 수.Second number.

반환Returnsf64 left > right 면 left, 아니면 right. (어느 쪽이든 NaN 이면 right)left if left > right, otherwise right. (right if either is NaN)

짝Counterpart: vanilla.js max

함수functionpub fn floor(value: f64) -> f64#0.4.0 부터since 0.4.0소스source

내림. (무한대는 그대로)

Floor. (infinity stays as is)

valuef64
내릴 수.Number to round down.

반환Returnsf64 value 이하에서 가장 큰 정수.The largest integer less than or equal to value.

짝Counterpart: vanilla.js floor

함수functionpub fn ceil(value: f64) -> f64#0.4.0 부터since 0.4.0소스source

올림. (무한대는 그대로)

Ceiling. (infinity stays as is)

valuef64
올릴 수.Number to round up.

반환Returnsf64 value 이상에서 가장 작은 정수.The smallest integer greater than or equal to value.

짝Counterpart: vanilla.js ceil

함수functionpub fn round(value: f64) -> f64#0.4.0 부터since 0.4.0소스source

반올림. (원본 round: 반은 +무한대 쪽으로, -2.5 → -2, -0.5 → 0, 무한대는 그대로)

Rounding. (the original round: halves toward +infinity, -2.5 → -2, -0.5 → 0, infinity stays as is)

valuef64
반올림할 수.Number to round.

반환Returnsf64 가장 가까운 정수. (반은 +무한대 쪽, NaN 과 무한대는 그대로)The nearest integer. (halves toward +infinity, NaN and infinity stay as is)

짝Counterpart: vanilla.js round

예제Example음수의 반은 위로 올린다Negative halves round up
use vanilla::math;

assert_eq!(math::round(2.5), 3.0);
assert_eq!(math::round(-2.5), -2.0);
assert_eq!(math::round(-2.6), -3.0);
assert_eq!(math::round(f64::INFINITY), f64::INFINITY);
함수functionpub fn sqrt(value: f64) -> f64#0.4.0 부터since 0.4.0소스source

제곱근. (음수는 NaN)

Square root. (NaN for negatives)

valuef64
제곱근을 구할 수.Number to take the square root of.

반환Returnsf64 제곱근. (음수면 NaN)Square root. (NaN for negative numbers)

짝Counterpart: vanilla.js sqrt

함수functionpub fn abs(value: f64) -> f64#0.4.0 부터since 0.4.0소스source

절대값. (원본처럼 0 보다 작으면 부호를 뒤집는다)

Absolute value. (flips the sign if less than 0, as in the original)

valuef64
절대값을 구할 수.Number to take the absolute value of.

반환Returnsf64 0 보다 작으면 -value, 아니면 value. (-0 과 NaN 은 그대로)-value if less than 0, otherwise value. (-0 and NaN stay as is)

짝Counterpart: vanilla.js abs

함수functionpub fn sin(value: f64) -> f64#0.4.0 부터since 0.4.0소스source

사인.

Sine.

valuef64
각. (라디안)Angle. (radians)

반환Returnsf64 사인 값. (-1 ~ 1)Sine value. (-1 ~ 1)

짝Counterpart: vanilla.js sin

함수functionpub fn cos(value: f64) -> f64#0.4.0 부터since 0.4.0소스source

코사인.

Cosine.

valuef64
각. (라디안)Angle. (radians)

반환Returnsf64 코사인 값. (-1 ~ 1)Cosine value. (-1 ~ 1)

짝Counterpart: vanilla.js cos

함수functionpub fn tan(value: f64) -> f64#0.4.0 부터since 0.4.0소스source

탄젠트.

Tangent.

valuef64
각. (라디안)Angle. (radians)

반환Returnsf64 탄젠트 값.Tangent value.

짝Counterpart: vanilla.js tan

함수functionpub fn asin(value: f64) -> f64#0.4.0 부터since 0.4.0소스source

아크사인. (범위 밖은 NaN)

Arcsine. (NaN outside the range)

valuef64
사인 값. (-1 ~ 1)Sine value. (-1 ~ 1)

반환Returnsf64 각. (라디안, -PI / 2 ~ PI / 2, 범위 밖이면 NaN)Angle. (radians, -PI / 2 ~ PI / 2, NaN if outside the range)

짝Counterpart: vanilla.js asin

함수functionpub fn acos(value: f64) -> f64#0.4.0 부터since 0.4.0소스source

아크코사인. (범위 밖은 NaN)

Arccosine. (NaN outside the range)

valuef64
코사인 값. (-1 ~ 1)Cosine value. (-1 ~ 1)

반환Returnsf64 각. (라디안, 0 ~ PI, 범위 밖이면 NaN)Angle. (radians, 0 ~ PI, NaN if outside the range)

짝Counterpart: vanilla.js acos

함수functionpub fn pow(base: f64, exponent: f64) -> f64#0.4.0 부터since 0.4.0소스source

거듭제곱. (지수가 분수나 음수여도 맞다)

Power. (correct even for fractional or negative exponents)

basef64
밑.Base.
exponentf64
지수.Exponent.

반환Returnsf64 base 의 exponent 제곱.base raised to the power of exponent.

짝Counterpart: vanilla.js pow

함수functionpub fn clamp(value: f64, minimum: f64, maximum: f64) -> f64#0.3.2 부터since 0.3.2소스source

범위 제한.

Clamps to a range.

valuef64
제한할 수.Number to clamp.
minimumf64
최소값.Minimum value.
maximumf64
최대값.Maximum value.

반환Returnsf64 value 가 minimum 보다 작으면 minimum, maximum 보다 크면 maximum, 아니면 value. (minimum 을 먼저 본다)minimum if value is less than minimum, maximum if greater than maximum, otherwise value. (minimum is checked first)

짝Counterpart: vanilla.js clamp

함수functionpub fn clamp01(value: f64) -> f64#0.3.2 부터since 0.3.2소스source

0 ~ 1 범위 제한.

Clamps to the 0 ~ 1 range.

valuef64
제한할 수.Number to clamp.

반환Returnsf64 0 ~ 1 로 자른 값.The value clamped to 0 ~ 1.

짝Counterpart: vanilla.js clamp01

함수functionpub fn degree_to_radian(degree: f64) -> f64#0.3.2 부터since 0.3.2소스source

도 → 라디안.

Degrees → radians.

degreef64
각. (도)Angle. (degrees)

반환Returnsf64 각. (라디안)Angle. (radians)

짝Counterpart: vanilla.js degreeToRadian

함수functionpub fn radian_to_degree(radian: f64) -> f64#0.3.2 부터since 0.3.2소스source

라디안 → 도.

Radians → degrees.

radianf64
각. (라디안)Angle. (radians)

반환Returnsf64 각. (도)Angle. (degrees)

짝Counterpart: vanilla.js radianToDegree

함수functionpub fn lerp(from: f64, to: f64, time: f64) -> f64#0.3.2 부터since 0.3.2소스source

선형 보간.

Linear interpolation.

fromf64
시작 값.Start value.
tof64
끝 값.End value.
timef64
보간 비율. (0 이면 from, 1 이면 to, 0 ~ 1 밖도 자르지 않는다)Interpolation ratio. (0 is from, 1 is to, values outside 0 ~ 1 are not clamped)

반환Returnsf64 from + (to - from) * time.

짝Counterpart: vanilla.js lerp

함수functionpub fn random() -> f64#0.3.2 부터since 0.3.2소스source

0 이상 1 미만 난수.

Random number from 0 inclusive to 1 exclusive.

반환Returnsf64 0 이상 1 미만 난수. (2 의 -24 제곱 단위, 스레드마다 상태를 따로 둔다)Random number from 0 inclusive to 1 exclusive. (in steps of 2 to the power of -24, each thread keeps its own state)

짝Counterpart: vanilla.js random

함수functionpub fn random_range(minimum: f64, maximum: f64) -> f64#0.3.2 부터since 0.3.2소스source

범위 난수. (minimum 이상 maximum 미만)

Random number in a range. (minimum inclusive to maximum exclusive)

minimumf64
범위 시작. (포함)Range start. (inclusive)
maximumf64
범위 끝.Range end.

반환Returnsf64 minimum + (maximum - minimum) * random().

짝Counterpart: vanilla.js randomRange

함수functionpub fn random_int(minimum: i32, maximum: i32) -> i32#0.4.0 부터since 0.4.0소스source

정수 범위 난수. (minimum 이상 maximum 이하)

Random integer in a range. (minimum to maximum inclusive)

minimumi32
가장 작은 값. (포함)Smallest value. (inclusive)
maximumi32
가장 큰 값. (포함)Largest value. (inclusive)

반환Returnsi32 minimum 이상 maximum 이하 정수.An integer from minimum to maximum inclusive.

짝Counterpart: vanilla.js randomInt

예제Example주사위 굴리기Roll a die
use vanilla::math;

let dice = math::random_int(1, 6);
assert!((1..=6).contains(&dice));
assert_eq!(math::random_int(5, 5), 5);
함수functionpub fn pick_random<T>(array: &[T]) -> Option<&T>#0.4.0 부터since 0.4.0소스source

배열에서 무작위로 하나. (비었으면 None, 원본 undefined)

One random element from an array. (None if empty, the original undefined)

array&[T]
고를 슬라이스.Slice to pick from.

반환ReturnsOption<&T> 무작위로 고른 원소의 참조. 비었으면 None.Reference to the randomly picked element. None if empty.

짝Counterpart: vanilla.js pickRandom

예제Example목록에서 하나 고르기Pick one from a list
use vanilla::math;

let item_list = ["sword", "shield", "potion"];
match math::pick_random(&item_list) {
	Some(item) => {
		assert!(item_list.contains(item));
	}
	None => {
		unreachable!();
	}
}
let empty_list: [i32; 0] = [];
assert!(math::pick_random(&empty_list).is_none());
함수functionpub fn shuffle<T>(array: &mut [T])#0.4.0 부터since 0.4.0소스source

배열 제자리 섞기. (Fisher-Yates, 엔진 random)

Shuffles an array in place. (Fisher-Yates, engine random)

array&mut [T]
섞을 슬라이스. (제자리에서 바뀐다)Slice to shuffle. (changed in place)

짝Counterpart: vanilla.js shuffle

함수functionpub fn shuffle_with_random_function<T>(array: &mut [T], mut random_function: impl FnMut() -> f64)#0.4.0 부터since 0.4.0소스source

넘긴 난수 함수(0 이상 1 미만)로 배열 제자리 섞기. (SeededRandom 의 next_value 등)

Shuffles an array in place with a passed random function (0 inclusive to 1 exclusive). (SeededRandom's next_value and such)

array&mut [T]
섞을 슬라이스. (제자리에서 바뀐다)Slice to shuffle. (changed in place)
random_functionimpl FnMut() -> f64
0 이상 1 미만을 돌려주는 함수. (원소 수 - 1 번 부른다, 1 이상이면 지금 자리로 자른다)Function returning 0 inclusive to 1 exclusive. (called element count - 1 times; values of 1 or more are clamped to the current position)
예제Example씨앗 난수로 늘 같은 차례 섞기Always shuffle in the same order with a seeded random
use vanilla::{math, SeededRandom};

let mut first_list = [1, 2, 3, 4, 5];
let mut second_list = [1, 2, 3, 4, 5];
let mut first_random = SeededRandom::new(42);
let mut second_random = SeededRandom::new(42);
math::shuffle_with_random_function(&mut first_list, || first_random.next_value());
math::shuffle_with_random_function(&mut second_list, || second_random.next_value());
assert_eq!(first_list, second_list);

let mut number_list = [1, 2, 3, 4];
math::shuffle_with_random_function(&mut number_list, || 0.0);
assert_eq!(number_list, [2, 3, 4, 1]);
함수functionpub fn approach(current_value: f64, target_value: f64, rate: f64, time_delta: f64) -> f64#0.3.2 부터since 0.3.2소스source

프레임률 독립 지수 감쇠 추종. (목표가 도중에 바뀌어도 튀지 않는다, rate 가 클수록 빨리 붙는다)

  • current + (target - current) * (1 - e^(-rate * time_delta))

Frame-rate independent exponential decay follow. (does not jump even if the target changes midway; the larger rate is, the faster it catches up)

  • current + (target - current) * (1 - e^(-rate * time_delta))
current_valuef64
지금 값.Current value.
target_valuef64
목표 값.Target value.
ratef64
붙는 빠르기. (시간 단위당, 클수록 빨리 붙는다, 0 이면 그대로)Catch-up speed. (per time unit, the larger the faster; unchanged if 0)
time_deltaf64
지난 시간. (rate 와 같은 시간 단위)Elapsed time. (in the same time unit as rate)

반환Returnsf64 목표 쪽으로 옮긴 값. (rate 와 time_delta 가 0 이상이면 지나치지 않는다)Value moved toward the target. (does not overshoot if rate and time_delta are 0 or more)

짝Counterpart: vanilla.js approach

예제Example매 프레임 목표를 부드럽게 따라가기Smoothly follow the target every frame
use vanilla::math;

let mut camera_x = 0.0;
for _ in 0..60 {
	camera_x = math::approach(camera_x, 100.0, 5.0, 1.0 / 60.0);
}
assert!(camera_x > 99.0 && camera_x < 100.0);
함수functionpub fn move_towards(current_value: f64, target_value: f64, maximum_delta: f64) -> f64#0.4.0 부터since 0.4.0소스source

값을 일정 속도로 목표까지 옮기기. (지나치지 않는다)

Moves a value toward the target at a constant speed. (does not overshoot)

current_valuef64
지금 값.Current value.
target_valuef64
목표 값.Target value.
maximum_deltaf64
한 번에 옮길 최대 거리. (0 이상)Maximum distance to move at once. (0 or more)

반환Returnsf64 maximum_delta 만큼 목표 쪽으로 옮긴 값. 남은 차이가 maximum_delta 이하이면 target_value.Value moved toward the target by maximum_delta. target_value if the remaining difference is maximum_delta or less.

짝Counterpart: vanilla.js moveTowards

예제Example일정 속도로 다가가고 넘지 않는다Approach at a constant speed without overshooting
use vanilla::math;

assert_eq!(math::move_towards(0.0, 10.0, 3.0), 3.0);
assert_eq!(math::move_towards(0.0, -10.0, 3.0), -3.0);
assert_eq!(math::move_towards(9.0, 10.0, 3.0), 10.0);
함수functionpub fn ease_out_quad(time: f64) -> f64#0.3.2 부터since 0.3.2소스source

이징: 바깥으로 감속하는 2차 곡선.

Easing: a quadratic curve decelerating outward.

timef64
진행 비율. (0 ~ 1)Progress ratio. (0 ~ 1)

반환Returnsf64 1 - (1 - time) * (1 - time). (0 이면 0, 1 이면 1)1 - (1 - time) * (1 - time). (0 at 0, 1 at 1)

짝Counterpart: vanilla.js easeOutQuad

상수Constants

상수constantpub const PI: f64 = std::f64::consts::PI#0.3.2 부터since 0.3.2소스source

원주율. (std::f64::consts::PI)

Pi. (std::f64::consts::PI)

반환Returnsf64

짝Counterpart: vanilla.js PI

상수constantpub const POSITIVE_INFINITY: f64 = f64::INFINITY#0.4.0 부터since 0.4.0소스source

양의 무한대. (원본 PositiveInfinity)

Positive infinity. (the original PositiveInfinity)

반환Returnsf64

짝Counterpart: vanilla.js PositiveInfinity

상수constantpub const NEGATIVE_INFINITY: f64 = f64::NEG_INFINITY#0.4.0 부터since 0.4.0소스source

음의 무한대. (원본 NegativeInfinity)

Negative infinity. (the original NegativeInfinity)

반환Returnsf64

짝Counterpart: vanilla.js NegativeInfinity