how to create random vector?
조회 수: 10(최근 30일)
표시 이전 댓글
hello,
I would like to know how I create a vector with random and integers 25 digit using round and randn?
Thanks.
댓글 수: 0
채택된 답변
Karim
2022년 7월 8일
RandomDouble = rand(25,1) % i.e. pick 25 random values between 0 and 1
RandomIntegers = randi(1000,25,1) % i.e. pick 25 integers between 1 and 1000
추가 답변(1개)
Voss
2022년 7월 8일
A vector of 5 random 19-digit numbers (change n_digits to 25 to get 25-digit numbers):
n_numbers = 5;
n_digits = 19;
digits = [randi(9,n_numbers,1) randi(10,n_numbers,n_digits-1)-1];
numbers = sum(digits.*10.^(n_digits-1:-1:0),2);
format long
disp(numbers);
sprintf('%19d\n',numbers)
댓글 수: 1
Steven Lord
2022년 7월 8일
Those numbers exceed flintmax so you're not generating the numbers you think you are. There are some (many) 19-digit numbers that your code cannot generate because they can't be represented in double precision.
rng default % for reproducibility
n_numbers = 1; % Let's just make 1 to start
n_digits = 19;
digits = [randi(9,n_numbers,1) randi(10,n_numbers,n_digits-1)-1]
That second randi call could be simplified a bit (to eliminate the subtraction) by specifying the first input as a vector.
randi([0 9], 1, 3)
Anyway, let's look at the number you created.
theNumber = polyval(digits, 10) % Another way to turn digits into a number
fromDouble = sprintf('%19d', theNumber)
Is it larger than flintmax? Yes.
isLargerThanFlintmax = theNumber > flintmax
Let's convert the numeric digits into the corresponding characters and compare.
fromDigits = sprintf('%s', char(digits + '0'))
Do they match?
[fromDouble; fromDigits]
Nope. Not all numbers are representable in double precision when the magnitude is in the vicinity of theNumber. The distance from theNumber to the next representable number is:
distance = eps(theNumber)
So adding something less than that distance to theNumber doesn't "get over the hump" to the next largest number.
isequal(theNumber, theNumber + 400)
참고 항목
범주
Find more on Random Number Generation in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!