Confusing problem about duration data

조회 수: 1 (최근 30일)
QIAO WANG
QIAO WANG 2019년 4월 12일
댓글: QIAO WANG 2019년 4월 16일
Hi,
I'm having a very confusing issue when I'm operating with duration data. I'm new to this data type. Here I debugged my code and simplify my question as an example. Please can someone point out the root reason of why this is not working. Basically, I first define a duration x and with this x, I want to create a new x1 with a random duration, like in the example. I describe my confusion as below. Can anyone help me out? I know it might be the problem of using rand but why?
x = duration(8,0,47);
>> x1 = x + rand*duration(0,0,10);
>> x1
x1 =
duration
08:00:54
However, I realize though x1 is of type of duration, it does not equal to the duration 08:00:54.
>> x1 == duration(8,0,54)
ans =
logical
0
Nevertheless, if I define a new x2 in a similar way, it works.
>> x2 = x + duration(0,0,7);
>> x2
x2 =
duration
08:00:54
>> x2 == duration(8,0,54)
ans =
logical
1
And x1 apparently doesn't equal to x2.
>> x1 == x2
ans =
logical
0

채택된 답변

Walter Roberson
Walter Roberson 2019년 4월 12일
rand() produces a 53 bit random number in the range 0 to 1, effectively randi([1 2^53-1],1,1) / 2^53
When you multiply this by 10 seconds, it is very unlikely to happen to result in an exact multiple of 1 second.
This is not obvious because the default output for duration does not display fractions of a second.
x1.Format = 'hh:mm:ss.SSSSSSSSS';
  댓글 수: 3
Walter Roberson
Walter Roberson 2019년 4월 16일
That is what you are getting now. A random duration of 7.846832 seconds is still a random duration within 10 seconds. The default format for duration just was not showing the fraction.
Perhaps
x + seconds(randi(10))
Note that randi(10) will not produce 0 but will produce 10.
QIAO WANG
QIAO WANG 2019년 4월 16일
Thank you very much! All sorted now!

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 MATLAB에 대해 자세히 알아보기

태그

아직 태그를 입력하지 않았습니다.

제품


릴리스

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by