Same function gives different answers while checking in a command window. why?
조회 수: 4 (최근 30일)
이전 댓글 표시
I am getting different answers when I want to check the answers of the file " pro.m" in the command window. I have attached my coding and screenshot of the ouput while running the code and output from the command window .Please anyone help me with this.
댓글 수: 2
Guillaume
2019년 1월 29일
I don't understand why you're surprised. Pass a random input to a function, expect a different output each time unless the function ignore your input.
Also, in your simm_opt.m:
x(1) = x;
y(1) = y;
is absurd. Either x is scalar, and the above is equivalent to x = x, pointless, or x is not scalar and the above will throw an error (trying to assign a non-scalar to a scalar).
Stephen23
2019년 1월 29일
편집: Stephen23
2019년 1월 29일
"Same function gives different answers while checking in a command window. why?"
Simple: you did not copy the full precison of the data, so your input values are not the same.
In particular, MATLAB's default format (which is short) is to display four decimal places, but this is not the full precision of the data stored in memory. You dutifully copied those values with those four decimal digits only... thus you provided different input data, because what you used as input values does not represent the full prevision of the original data.
Change the format to something with more digits, e.g.:
format long
and then display the values with more precision and copy them again. Even better would be to use exactly the same values by not copy-and-pasting, but by simply referring to the same matrix x0.
EDIT: Note that Rajashree Annapillai has since deleted the uploaded files, making all of the answers totally meaningless as they have no context.
채택된 답변
Jan
2019년 1월 29일
편집: Jan
2019년 1월 29일
Your input is created by rand. This creates floating point numbers with about 16 significant digits. For convenience they are displayed with 4 decimals, when you use
format short
See the details: doc format
To see more digits use e.g.: format long g
When you copy only the first 4 digits of the number, the result is different, of course.
By the way, 10^5 is an expensive power operation, while 1e5 is a cheap constant.
댓글 수: 0
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!