Precision of num2str function

조회 수: 9 (최근 30일)
Panagiotis Artemiou
Panagiotis Artemiou 2023년 4월 5일
댓글: Panagiotis Artemiou 2023년 4월 9일
I try to make o PRNG using the middle square method.
When I come the the point where I need to keep the middle digits of a number. I convert from double to string.
The precision is set in the function as 8. But after 70 iterations it does not have the the desired precision when converting from double to string.
The code can be seen bellow.
format long
seed=2315;
m=256;
z(1)=seed;
for i=2:m
z(i-1)=z(i-1)^2;
u(i-1)=z(i-1)/(10^(2*4));
t=convertStringsToChars(num2str(u(i-1),8));
temp=t(5:8);
temp=str2double(temp);
z(i)=temp;
end
For example when i=69 u(i-1)=0.06270016 and when it converts to string and then char it becomes '0.06270016'
And when i=70 u(i-1)=0.07290000 but this becomes '0.0729'.
How can I make it be '0.07290000' after the conversion?

채택된 답변

Stephen23
Stephen23 2023년 4월 5일
편집: Stephen23 2023년 4월 5일
If you want that much control over the text format then you should be using SPRINTF.
But in lieu of that, you can specify the format string with NUM2STR:
num2str(0.06270016,'%.8f')
ans = '0.06270016'
num2str(0.0729,'%.8f')
ans = '0.07290000'
  댓글 수: 1
Panagiotis Artemiou
Panagiotis Artemiou 2023년 4월 9일
Thank you very much. This was really helpful!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

제품


릴리스

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by