在python中将float转换为整数的最安全方法? [英] Safest way to convert float to integer in python?

查看:808
本文介绍了在python中将float转换为整数的最安全方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python的数学模块包含便利的函数,如 floor & 小区。这些函数采用浮点数并返回低于或高于它的最接近的整数。但是,这些函数将答案作为浮点数返回。例如:

Python's math module contain handy functions like floor & ceil. These functions take a floating point number and return the nearest integer below or above it. However these functions return the answer as a floating point number. For example:

import math
f=math.floor(2.3)

现在 f 返回:

2.0

获取整数的最安全的方法是什么这个浮点数,没有运行舍入错误的风险(例如,如果浮点数相当于1.99999)或者我应该完全使用另一个函数?

What is the safest way to get an integer out of this float, without running the risk of rounding errors (for example if the float is the equivalent of 1.99999) or perhaps I should use another function altogether?

推荐答案

可以用浮点数表示的所有整数都有精确的表示。因此,您可以安全地在结果上使用 int 。只有当你试图用一个不是2的幂的分母来表示一个有理数时才会出现不精确的表示。

All integers that can be represented by floating point numbers have an exact representation. So you can safely use int on the result. Inexact representations occur only if you are trying to represent a rational number with a denominator that is not a power of two.

这个工作并不是微不足道的!它是IEEE浮点表示的一个属性,如果所讨论的数字的大小足够小,则int∘floor=⌊⋅⌋,但int(floor(2.3))可能为1时可能有不同的表示。

That this works is not trivial at all! It's a property of the IEEE floating point representation that int∘floor = ⌊⋅⌋ if the magnitude of the numbers in question is small enough, but different representations are possible where int(floor(2.3)) might be 1.

引用维基百科


任何绝对值小于或等于2的整数 24 可以用单精度格式精确表示,绝对值小于或等于2 53 的任何整数都可以用双精度格式精确表示。

Any integer with absolute value less than or equal to 224 can be exactly represented in the single precision format, and any integer with absolute value less than or equal to 253 can be exactly represented in the double precision format.

这篇关于在python中将float转换为整数的最安全方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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