Are there any functions for taking the most/least significant digits from a given value?

조회 수: 4 (최근 30일)
Title kinda says it all.
If there isn't a function, can anyone think of a way of writing one to do it efficiently? I'm generating long streams of outputs (experimenting with random number generator implementations) and don't want to bog the whole thing down running a ton of weird arithmetic just to lop a few digits off one end of the output.
Thanks in advance
Will
  댓글 수: 2
Walter Roberson
Walter Roberson 2011년 2월 4일
Are these integers or floating point numbers? There are relatively few floating point numbers that can be truncated to a decimal number that happens to be exactly representable as a binary floating point number.
Will
Will 2011년 2월 4일
All is good, the answer below sorted me out just fine. Thanks for asking though :)

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

채택된 답변

Davide Ferraro
Davide Ferraro 2011년 2월 4일
If I'm correctly understanding your question you would like to extract some digits from a number.
The mathematical approach is simply based on multiplication/division by powers of 10 and then using REM or MOD you can extract the number you are interested in.
>> A = 123.456;
>> rem(A,1)
ans =
0.4560
>> rem(A,10)
ans =
3.4560
You can then rescale this number appropriately to your needs.
Another way to work on the position is simply to convert the number into a string with NUM2STR and then index into the string to extract the desired value. String conversion has an additional computational cost but may be easier if you just need to operate on digits. With STR2DOUBLE you can convert the value back if you need to do additional arithmetic operations.

추가 답변 (0개)

카테고리

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

제품

Community Treasure Hunt

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

Start Hunting!

Translated by