str2double conversion error

8 ビュー (過去 30 日間)
John Jendzurski
John Jendzurski 2020 年 5 月 30 日
編集済み: Adam Danz 2020 年 5 月 30 日
Is there a way to avoid this sort of error/effect (see code below) when converting a string to a double? I have tried using str2num() but get the same result.Thanks!
>> str2double('39.11237316')
ans =
39.112373159999997

採用された回答

Adam Danz
Adam Danz 2020 年 5 月 30 日
編集済み: Adam Danz 2020 年 5 月 30 日
You're witnessing floating point roundoff error. In short, an infinite range of numbers must be represented in a finite number of bits (specifically, 64 for double precision numbers). The number you're trying to represent doesn't fit perfectly in this system so it's rounded.
Check this out.
format long
x = 39.11237316
% x =
% 39.112373159999997
% Even if you round it to 8 dp, it can't be represeneted
round(x,8)
% ans =
% 39.112373159999997
So, it's not the str2double() that is the problem, it's the finite precision that this number can be represented in.
If higher precision is required you can use symbolic representation for your computations. But the difference between your value and the value being represented is very tiny and usually not a problem.
For a wonderful explanation of floating point roundoff error, see Cleve Moler's article (founder of Matlab).
  2 件のコメント
John Jendzurski
John Jendzurski 2020 年 5 月 30 日
編集済み: John Jendzurski 2020 年 5 月 30 日
That's a very helpful, clear, and excellent description of what is happening. Thanks, Adam!
Adam Danz
Adam Danz 2020 年 5 月 30 日
Thanks for the feedback, John. Glad I could help.

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

その他の回答 (0 件)

カテゴリ

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

製品


リリース

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by