Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/301.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使Python停止对非常接近的数字进行舍入?_Python - Fatal编程技术网

如何使Python停止对非常接近的数字进行舍入?

如何使Python停止对非常接近的数字进行舍入?,python,Python,我制作这个算法是为了测试python如何比较接近的数字 x = 2.5 # arbitrary number chosen to do the testing y = float(input('Insert Y ')) # print('X > Y = {}'.format(x > y)) # shows whether x>y print('X = Y = {}'.format(x ==

我制作这个算法是为了测试python如何比较接近的数字

x = 2.5                                # arbitrary number chosen to do the testing
y = float(input('Insert Y '))        # 
print('X > Y = {}'.format(x > y))      # shows whether x>y
print('X = Y = {}'.format(x == y))     # shows whether x = y
print('X < Y = {}'.format(x < y))      # shows whether x < y
x=2.5#选择任意数字进行测试
y=浮动(输入(“插入y”)#
打印('X>Y={}'。格式(X>Y))#显示X>Y
打印('X=Y={})。格式(X==Y))#显示X=Y
打印('X
对于y=2.50000000000000001,它具有Python自动将数字四舍五入的最小小数位数。 执行:

Insert Y 2.50000000000000001
X > Y = False
X = Y = True
X < Y = False

Process finished with exit code 0
插入Y 2.50000000000000001
X>Y=False
X=Y=True
X
如何让Python意识到X小于Y,而不是四舍五入?

实数(例如2.5)在Python中以浮点数格式表示。 浮点数表示为符号*尾数*2^指数,例如3.0=1.5*2^1。 每个部分(符号、尾数、指数)都存储为整数

现在,为了表示您的数字2.50000000000000001,您需要存储整数2500000000000000001,它需要ceil(log2(2500000000000000001))=58位。 但对于float64(几乎总是在Python中使用),尾数是52位大,太小了,无法容纳这个数字

将输入读入浮点表示时,会进行舍入,以获得与输入可能最接近的数字。
这就是为什么在您的示例中X和Y相等。

X
不小于
Y
。您明确使用的是基2 64位浮点数(也称为
float
),其
2.50000000001
正好等于
2.5
。这是否回答了您的问题?这回答了你的问题吗?简单地执行
y=float(“2.50000000001”)
然后
print(y)
将向您揭示
y
实际上是
2.5
。。。