歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Matlab中的取整函數fix, floor, ceil與round

Matlab中的取整函數fix, floor, ceil與round

日期:2017/3/1 9:52:20   编辑:Linux編程

Matlab中的取整函數fix, floor, ceil與round

1. fix 向0取整

fix([-0.5 -0.4 0.4 0.5]) ==> [0 0 0 0]

2. floor 向-inf取整

floor([-0.5 -0.4 0.4 0.5]) ==> [- 1 -1 0 0]

3. ceil 向+inf取整

ceil([-0.5 -0.4 0.4 0.5]) ==> [0 0 1 1]

4. round 四捨五入

round([-0.5 -0.4 0.4 0.5]) ==> [-1 0 0 1]

最開始用matlab時,程序中涉及到取整,因為使用C, C++等其他編程語言的原因,首先想到的是直接強制轉換,使用int32(),結果如下,令我有點吃驚,居然和round效果一樣,四捨五入。

int32([-0.5 -0.4 0.4 0.5]) ==> [-1 0 0 1]% 注意數據類型double已變為int32

但在C, C++中,int取整是向0取整,與matlab中的fix()效果一樣,測試代碼如下:

int main()
{
double data[] = {-1.5, -0.5, -0.4, 0.4, 0.5, 1.5};
for (size_t i=0; i<6; ++i)
cout << int(data[i]) << "\t" << (int)data[i] << endl;

getchar();
return 0;
}

輸出結果:

-1 -1
0 0
0 0
0 0
0 0
1 1

故寫這篇文章記錄下,供自己及他人查閱,歡迎討論。

Copyright © Linux教程網 All Rights Reserved