对于大数,为什么整数除法和除法转换为int的结果不同? [英] Why are the results of integer division and converting to an int after division different for large numbers?

查看:81
本文介绍了对于大数,为什么整数除法和除法转换为int的结果不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

print(10**40//2)
print(int(10**40/2))

代码输出:

5000000000000000000000000000000000000000
5000000000000000151893014213501833445376

为什么值不同?为什么第二个 print()的输出看起来如此?

Why different values? Why the output of the second print() looks so?

推荐答案

10 ** 40 // 2 的浮点表示不准确:

>>> format(float(10**40//2), '.0f')
'5000000000000000151893014213501833445376'

那是因为浮点算法只是一个近似值,尤其是当您超出了CPU可以准确建模的范围时(因为浮点是在硬件中处理的。)

That's because floating point arithmetic is only ever an approximation, especially when you go beyond what your CPU can accurately model (as floating point is handled in hardware).

整数除法不必将 10 ** 40 数字表示为浮点数,它只需要除以整数即可,在Python中整数可以任意取大而不会造成精度损失。

The integer division never has to represent the 10**40 number as a float, it only has to divide the integer, which in Python can be arbitrarily large without precision loss.

另请参见:

  • Floating Point Arithmetic: Issues and Limitations in the Python tutorial
  • What Every Programmer Should Know About Floating-Point Arithmetic
  • What Every Computer Scientist Should Know About Floating-Point Arithmetic

十进制模块如果必须使用更高精度的浮点运算。

Also look at the decimal module if you must use higher-precision floating point arithmetic.

这篇关于对于大数,为什么整数除法和除法转换为int的结果不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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