You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

寻找无法通过字符串往返转换的最短有效浮点数字符串

问题描述

给定规则:

  • 对于十进制实数字符串s,to_float(s)返回最接近该数的IEEE双精度浮点数
  • 对于IEEE双精度浮点数f,to_string(f)(基于Dragon4算法)返回最短的字符串fs,使得to_float(fs) == f

求满足to_string(to_float(s)) != s的最短有效非NaN有限浮点数字符串

尝试的暴力枚举代码

我通过暴力枚举检查了最多7位数字加小数点的字符串,代码如下:

import numpy as np
import itertools

def check_numbers_up_to_n_digits(n):
    STR = np.format_float_positional
    FLOAT = float
    rngs = [tuple(range(1, i)) for i in range(n + 1)]
    for x in map(''.join, itertools.product('0123456789', repeat=n)):
        x = x.rstrip('0')
        if x == '': continue
        if x[0] == '0':
            s = '0.' + x[1:]
            if STR(FLOAT(s)) != s:
                print(repr(s))
            continue
        for d in rngs[len(x)]:
            s = x[:d] + '.' + x[d:]
            if s[-1] != '.' and STR(FLOAT(s)) != s:
                print(repr(s))

注:这段代码会过滤掉末尾带零的字符串(x.rstrip('0')),因此无法检测到类似0.0、01这类符合条件的短字符串。

答案

如果允许非规范格式的浮点数(如带前导零的整数、末尾带零的小数),最短的符合条件的字符串是长度为2的01(或02至09、00):

  • 以01为例:to_float("01")得到双精度浮点数1.0,而to_string(1.0)返回最短表示"1",显然"1" != "01"。

如果要求字符串为规范格式(无前导零、小数部分末尾无冗余零、整数部分非零时不能为单个零加小数点),则最短的符合条件的字符串是长度为3的0.0(或1.0、-1.0等):

  • 以0.0为例:to_float("0.0")得到0.0,to_string(0.0)返回最短表示"0","0" != "0.0"。

内容的提问来源于stack exchange,提问作者Felipe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 09:15:33