9

floor、ceil、round、trunc函数都是什么?

 2 years ago
source link: https://allenwind.github.io/blog/12387/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
Mr.Feng Blog

NLP、深度学习、机器学习、Python、Go

floor、ceil、round、trunc函数都是什么?

日常编程中,你是否也遇到过取值问题时面对这样的函数floor、ceil、round、trunc,今天来介绍一下这些函数。

floor函数

floor函数,又称为下取整函数,在数学中如下表示

floor(x)=⌊x⌋floor⁡(x)=⌊x⌋

其意义是最大整数小于或等于xx。我们拿numpy来尝试一下:

>>> import numpy as np
>>> np.floor(1.2)
1.0
>>> np.floor(1.8)
1.0
>>> np.floor(-3.2)
-4.0
>>> np.floor(-3.8)
-4.0
>>> np.floor(0)
0.0
>>>

ceil函数

ceil函数,又称为上取整函数,在数学中如下表示

ceil(x)=⌈x⌉ceil⁡(x)=⌈x⌉

其意义是最小整数大于或等于xx。我们拿numpy来尝试一下:

>>> import numpy as np
>>> np.ceil(1.2)
2.0
>>> np.ceil(1.8)
2.0
>>> np.ceil(-3.2)
-3.0
>>> np.ceil(-3.8)
-3.0

根据ceil函数和floor函数的特点,我们不难得出

floor(x)=⌊x⌋=−⌈−x⌉floor⁡(x)=⌊x⌋=−⌈−x⌉ ceil(x)=⌈x⌉=−⌊−x⌋ceil⁡(x)=⌈x⌉=−⌊−x⌋

round函数

round函数就是我们日常中说的四舍五入,或者说返回离其最近的整数。这个函数在tensorflow也是类似的定义,

>>> print(tf.math.round.__doc__)
Rounds the values of a tensor to the nearest integer, element-wise.

Rounds half to even. Also known as bankers rounding. If you want to round
according to the current system rounding mode use tf::cint.
For example:

python
x = tf.constant([0.9, 2.5, 2.3, 1.5, -4.5])
tf.round(x) # [ 1.0, 2.0, 2.0, 2.0, -4.0 ]
Args:
x: A `Tensor` of type `float16`, `float32`, `float64`, `int32`, or `int64`.
name: A name for the operation (optional).

Returns:
A `Tensor` of same shape and type as `x`.

numpy演示

>>> np.round(1.4)
1.0
>>> np.round(1.5)
2.0
>>> np.round(-1.4)
-1.0
>>> np.round(-1.5)
-2.0

trunc函数

trunc函数可以用ceil、floor函数定义,看起来有点复杂,

trunc(x,n)=⎧⎪⎨⎪⎩⌊10n⋅x⌋10nx∈R+⌈10n⋅x⌉10nx∈R−trunc⁡(x,n)={⌊10n⋅x⌋10nx∈R+⌈10n⋅x⌉10nx∈R−

默认情况下n取0,即截断小数部分。用numpy来演示可以直观地理解,

>>> np.trunc(1.1)
1.0
>>> np.trunc(1.5)
1.0
>>> np.trunc(1.51)
1.0
>>> np.trunc(-1.4)
-1.0
>>> np.trunc(-1.51)
-1.0

上取整函数(ceil)和下取整函数(floor)的名称其实来自英文的ceiling(天花板)和floor(地板),因此很好记忆。

转载请包括本文地址:https://allenwind.github.io/blog/12387
更多文章请参考:https://allenwind.github.io/blog/archives/


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK