generate (not round) 2 decimal numbers
이전 댓글 표시
Hello, in the first part of more complicated calculation I need some restriction to "rand" or so. My point is a reduction of unnecessary calculations and occurence of crowding results by simplification of the random number choice to 2 decimals in the first place. Is it possible?
Thank you
댓글 수: 3
José-Luis
2016년 9월 14일
What do you mean by simplify calculations? If you are using the double format anyway, I very much doubt that the computational requirements will differ much. A probably better approach is only to round when you have your final result.
José-Luis
2016년 9월 14일
The you need to use a format other than double. I am afraid "reducing" the number of decimals will do nothing for you, the number will still be stored as a double and will continue to use the same amount of memory.
Please explain what you are trying to achieve in order to help you better.
답변 (2개)
Are you looking for something like this?
sprintf('%3.2f',rand(1,1))
Here are two methods of providing random numbers rounded to two decimal places:
>> randi([0,100],5)/100
ans =
0.8200 0.0900 0.1500 0.1400 0.6600
0.9100 0.2800 0.9800 0.4200 0.0300
0.1200 0.5500 0.9600 0.9200 0.8500
0.9200 0.9600 0.4900 0.8000 0.9400
0.6300 0.9700 0.8000 0.9600 0.6800
>> round(100*rand(5))/100
ans =
0.7600 0.7100 0.8200 0.4400 0.4900
0.7400 0.0300 0.6900 0.3800 0.4500
0.3900 0.2800 0.3200 0.7700 0.6500
0.6600 0.0500 0.9500 0.8000 0.7100
0.1700 0.1000 0.0300 0.1900 0.7500
Note that you also need to understand the behaviors of floating point numbers:
댓글 수: 1
Walter Roberson
2016년 9월 14일
Note: if memory space is a problem then you can use
randi([0,100], 5, 'uint8')
and adjust the rest of your algorithm to expect these to be 100 times too large. It probably will not help much in practice... it will probably lead to more problems than it is worth.
카테고리
도움말 센터 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!