是否有工具可以知道一个值是否具有作为浮点变量的精确二进制表示? [英] Is there a tool to know whether a value has an exact binary representation as a floating point variable?

查看:7
本文介绍了是否有工具可以知道一个值是否具有作为浮点变量的精确二进制表示?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 C API 有一个将 double 作为输入的函数.只有 3 或 4 个值是有效输入,所有其他值都是无效输入并被拒绝.

My C API has a function that takes as input a double. Only 3 or 4 values are valid input, all other values are non valid input and rejected.

我想检查我的所有有效输入值是否可以准确表示,这样我就可以避免进行 epsilon 检查以提高可读性.

I'd like to check if all my valid input values can be represented exactly so that I could avoid the epsilon check to ease readability.

是否有工具(最好在命令行上)可以告诉我十进制值是否具有精确的二进制表示为浮点值?

Is there a tool (preferably on command line) that could tell me whether a decimal value has an exact binary representation as a floating point value?

推荐答案

这是一个 Python 代码片段,它完全符合您的要求;它需要 Python 2.7 或 Python 3.x.(早期版本的 Python 对浮点转换不太谨慎.)

Here's a Python snippet that does exactly what you ask for; it needs Python 2.7 or Python 3.x. (Earlier versions of Python are less careful with floating-point conversions.)

import decimal, sys
input = sys.argv[1]
if decimal.Decimal(input) == float(input):
    print("Exactly representable")
else:
    print("Not exactly representable")

用法:将脚本保存在名称'exactly_representable.py'下后,

Usage: after saving the script under the name 'exactly_representable.py',

mdickinson$ python exactly_representable.py 1.25
Exactly representable
mdickinson$ python exactly_representable.py 0.1
Not exactly representable
mdickinson$ python exactly_representable.py 1e22
Exactly representable
mdickinson$ python exactly_representable.py 1e23
Not exactly representable

这篇关于是否有工具可以知道一个值是否具有作为浮点变量的精确二进制表示?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆