How to comparison decimal numbers
Ältere Kommentare anzeigen
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 Kommentare
Walter Roberson
am 1 Dez. 2015
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
am 2 Dez. 2015
Akzeptierte Antwort
Weitere Antworten (2)
Image Analyst
am 2 Dez. 2015
1 Stimme
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
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 Kommentare
Image Analyst
am 2 Dez. 2015
Or simply
xr = round(x, 5);
unless one is using an antique version of MATLAB.
Walter Roberson
am 2 Dez. 2015
1.234563 rounds to 1.23456
1.234565 rounds to 1.23457
but the numbers differ by only 0.000002
This is why it is necessary to know whether the question is about whether the values are equal when rounded or if the question is whether the values differ by less than a threshold.
Thar
am 2 Dez. 2015
Image Analyst
am 2 Dez. 2015
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
am 2 Dez. 2015
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?
Kategorien
Mehr zu Logical finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!