LoginSignup
3
1

More than 5 years have passed since last update.

[#matlab] double型の数字が整数かどうか判定する

Last updated at Posted at 2016-01-08

intro

matlabでdouble型が基本的に出力されますがそれが整数なのかどうかを判定する関数を書きます。

地味に重要な気がする。

method

eps関数がキモです。
epsironの略だと思うんですけど、許容誤差みたいなもんですね。
eps('double')はdoubleの最小誤差ってことだと思います。
double型のintegerなら、round(四捨五入)して差をとっても完全にゼロになるので、差がeps('double')より小さくなるということみたいです。

IsInteger = @(x) (abs(round(x)-x)) <= eps('double');
a = 0.01;
b = 1.00;

isinteger(a)
isinteger(b)
IsInteger(a)
IsInteger(b)
% results below
% ans =
%      0
% ans =
%      0
% ans =
%      0
% ans =
%      1 % only `IsInteger` can tell if the number is integer or not

reference

MATLAB Central - Finding out if a floating point number is integer.

3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1