How to comparison decimal numbers

57 ビュー (過去 30 日間)
Thar
Thar 2015 年 12 月 1 日
コメント済み: Walter Roberson 2015 年 12 月 2 日
Hi all!
I have two matrices. They have one column. First matrix is:
7.551119
7.551154
7.551189
7.551224
Second matrix is:
7.551111
7.551146
7.551181
7.551215
I want to comparison two columns but only 5 decimal places. I don't like round my numbers like:
7.55112
7.55115
and so on, if I use the function round.
  2 件のコメント
Walter Roberson
Walter Roberson 2015 年 12 月 1 日
When you say that you want to compare to 5 decimal places, do you mean that when printed out rounded to 5 decimal places the numbers must match, or do you mean that the difference between the two numbers must be less than 10^(-5) ? Or at most 1/2 * 10^(-5) ?
Thar
Thar 2015 年 12 月 2 日
I want to keep the 5 decimal points, but not rounded the numbers. for example for the number 7.551187 i want to keep only the 7.55118 and not round to 7.55119.

サインインしてコメントする。

採用された回答

arich82
arich82 2015 年 12 月 2 日
You can truncate (without rounding) using floor (or fix, if your numbers can be negative):
x = [ ...
7.551119; ...
7.551154; ...
7.551189; ...
7.551224; ...
];
y = fix(x*1e5)/1e5;
output:
y =
7.551110000000000
7.551150000000000
7.551180000000000
7.551220000000000
  1 件のコメント
Thar
Thar 2015 年 12 月 2 日
Thank you!!

サインインしてコメントする。

その他の回答 (2 件)

Image Analyst
Image Analyst 2015 年 12 月 2 日
You need to use a tolerance. See the FAQ for a complete explanation: http://matlab.wikia.com/wiki/FAQ#Why_is_0.3_-_0.2_-_0.1_.28or_similar.29_not_equal_to_zero.3F

Thorsten
Thorsten 2015 年 12 月 2 日
編集済み: Thorsten 2015 年 12 月 2 日
You can round to 5 decimal places using
xr = round(x*1e5)/1e5;
You may want to set
format long
such that the result is properly displayed.
  5 件のコメント
Image Analyst
Image Analyst 2015 年 12 月 2 日
Then don't round (as I suspected you shouldn't). Use the tolerance like I told you in my answer where I referred you to the FAQ.
Walter Roberson
Walter Roberson 2015 年 12 月 2 日
To check, Thodoris, you are okay with 7.551111 comparing equal to 7.551119, but 7.551119 should not compare equal to 7.551121 even though that is closer to it than 7.551111 is?

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

タグ

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by