Skip to content

# Module `mbcp.mp_math.utils` ​

本模块定义了一些常用的工具函数

### func `clamp(x: float, min_: float, max_: float) -> float` ​

Description: 区间限定函数

Arguments:

> - x (`float`): 值
> - min_ (`float`): 最小值
> - max_ (`float`): 最大值

Return: `float`: 限定在区间内的值

Source code or View on GitHub
python

    def clamp(x: float, min_: float, max_: float) -> float:
        return max(min(x, max_), min_)

### class `Approx` ​

#### method `__init__(self, value: RealNumber)` ​

Description: 用于近似比较对象

Arguments:

> - value (`RealNumber`): 实数

Source code or View on GitHub
python

    def __init__(self, value: RealNumber):
        self.value = value

#### method `self == other` ​

Source code or View on GitHub
python

    def __eq__(self, other):
        if isinstance(self.value, (float, int)):
            if isinstance(other, (float, int)):
                return abs(self.value - other) < APPROX
            else:
                self.raise_type_error(other)
        elif isinstance(self.value, Vector3):
            if isinstance(other, (Vector3, Point3, Plane3, Line3)):
                return all([approx(self.value.x, other.x), approx(self.value.y, other.y), approx(self.value.z, other.z)])
            else:
                self.raise_type_error(other)

#### method `raise_type_error(self, other)` ​

Source code or View on GitHub
python

    def raise_type_error(self, other):
        raise TypeError(f'Unsupported type: {type(self.value)} and {type(other)}')

#### method `self != other` ​

Source code or View on GitHub
python

    def __ne__(self, other):
        return not self.__eq__(other)

### func `approx(x: float, y: float = 0.0, epsilon: float = APPROX) -> bool` ​

Description: 判断两个数是否近似相等。或包装一个实数，用于判断是否近似于0。

Arguments:

> - x (`float`): 数1
> - y (`float`): 数2
> - epsilon (`float`): 误差

Return: `bool`: 是否近似相等

Source code or View on GitHub
python

    def approx(x: float, y: float=0.0, epsilon: float=APPROX) -> bool:
        return abs(x - y) < epsilon

### func `sign(x: float, only_neg: bool = False) -> str` ​

Description: 获取数的符号。

Arguments:

> - x (`float`): 数
> - only_neg (`bool`): 是否只返回负数的符号

Return: `str`: 符号 + - ""

Source code or View on GitHub
python

    def sign(x: float, only_neg: bool=False) -> str:
        if x > 0:
            return '+' if not only_neg else ''
        elif x < 0:
            return '-'
        else:
            return ''

### func `sign_format(x: float, only_neg: bool = False) -> str` ​

Description: 格式化符号数 -1 -> -1 1 -> +1 0 -> ""

Arguments:

> - x (`float`): 数
> - only_neg (`bool`): 是否只返回负数的符号

Return: `str`: 符号 + - ""

Source code or View on GitHub
python

    def sign_format(x: float, only_neg: bool=False) -> str:
        if x > 0:
            return f'+{x}' if not only_neg else f'{x}'
        elif x < 0:
            return f'-{abs(x)}'
        else:
            return ''