确定数字是否在 float 或 double 的范围内

问题描述 投票:0回答:1

有没有办法确定一个数字是否可以存储为单浮点数或双浮点数?
我正在实现我自己的数据库格式,并在我的辅助函数中

num2bin(n)
我目前有以下代码:

import struct, warnings

def num2bin(n:int|float) -> bytes:
    match type(n).__name__:
        case 'int':
            ... # Excluded because unimportant to this question 
        case 'float':
            try:
                return struct.pack('>f', n)
            except struct.error:
                try:
                    return struct.pack('>d', n)
                except struct.error:
                    warnings.warn(f"num2bin(n): Failed to store {n} as float or double")
                    return b''
        case other:
            warnings.warn(f"num2bin(n): 'n' is of type '{other}' (must be 'int' or 'float')")
            return b''

有没有更好、更优雅的方法来确定我是否可以将数字存储为浮点数(

f
)或双精度(
d
)?
我认为一定有更好的方法来做到这一点,而不是仅仅尝试并捕获错误?

python-3.x floating-point precision
1个回答
0
投票

我不完全确定它是否会包含所有浮动,但我现在进行这些检查:

import struct, warnings

def num2bin(n:int|float) -> bytes:
    match type(n).__name__:
        case 'int':
            ... # Excluded because unimportant to this answer 
        case 'float':
            if unsigned:
            fltmax:tuple[float] = struct.unpack(
                '>ff',
                b'\x019Dp\x7f\x7f\xff\xff'
                # Min and max single-precision float value (2.2250738585072014e-308, 1.7976931348623157e+308)
            )
            dblmax:tuple[float] = struct.unpack(
                '>dd',
                b'\x00\x10\x00\x00\x00\x00\x00\x00\x7f\xef\xff\xff\xff\xff\xff\xff'
                # Min and max double-precision float value (3.402823507664669e-38, 3.4028234663852886e+38)
            )
            if (n>fltmax[0])and(fltmax[1]>n):
                return struct.pack('>f', n)
            elif (n>dblmax[0])and(dblmax[1]>n):
                return struct.pack('>d', n)
            else:
                warnings.warn(f"num2bin(n): Failed to store {n} as float or double")
                return b''
        case other:
            warnings.warn(f"num2bin(n): 'n' is of type '{other}' (must be 'int' or 'float')")
            return b''

因为浮点数既可能很大且不精确,也可能很小但很精确,我不确定这是否包括所有浮点数,或者对于某些实际上可存储为浮点数或双精度浮点数的浮点数会失败...

© www.soinside.com 2019 - 2024. All rights reserved.