Skip to content

Instantly share code, notes, and snippets.

@DuceMonster

DuceMonster/MathUtil.cs

Last active Jan 29, 2021
Embed
What would you like to do?
Unityの丸め誤差による問題の回避
using UnityEngine;
/// <summary>
/// 数値計算ユーティリティ
/// </summary>
public static class MathUtil
{
/// <summary>
/// 計算機イプシロン
/// </summary>
private const float Epsilon = 1E-06f;
/// <summary>
/// 小数を切り捨て
/// </summary>
/// <param name="value">値</param>
/// <returns>切り捨てられた値</returns>
public static float Floor(float value) => Mathf.Floor(value + Epsilon);
/// <summary>
/// 小数を切り上げ
/// </summary>
/// <param name="value">値</param>
/// <returns>切り上げられた値</returns>
public static float Ceil(float value) => Mathf.Ceil(value - Epsilon);
/// <summary>
/// aとbが近似しているかを取得
/// </summary>
/// <param name="a">値</param>
/// <param name="b">値</param>
/// <returns>aとbが近似しているか (true: そう, false: 違う)</returns>
public static bool Approximately(float a, float b) => Mathf.Abs(b - a) < Epsilon;
/// <summary>
/// aがbより大きいかを取得
/// </summary>
/// <param name="a">値</param>
/// <param name="b">値</param>
/// <returns>aがbより大きいか (true: そう, false: 違う)</returns>
public static bool GreaterThan(float a, float b) => a > b + Epsilon;
/// <summary>
/// aがb以上かを取得
/// </summary>
/// <param name="a">値</param>
/// <param name="b">値</param>
/// <returns>aがb以上か (true: そう, false: 違う)</returns>
public static bool GreaterThanOrEqual(float a, float b) => a > b - Epsilon;
/// <summary>
/// aがbより小さいかを取得
/// </summary>
/// <param name="a">値</param>
/// <param name="b">値</param>
/// <returns>aがbより小さいか (true: そう, false: 違う)</returns>
public static bool LessThan(float a, float b) => a < b - Epsilon;
/// <summary>
/// aがb以下かを取得
/// </summary>
/// <param name="a">値</param>
/// <param name="b">値</param>
/// <returns>aがb以下か (true: そう, false: 違う)</returns>
public static bool LessThanOrEqual(float a, float b) => a < b + Epsilon;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment