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

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

问题描述

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.

引用维基百科,

任何绝对值小于等于224的整数都可以用单精度格式精确表示,任何绝对值小于等于253的整数sup> 可以用双精度格式精确表示.

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中将浮点数转换为整数的最安全方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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