how to create random vector?

조회 수: 5(최근 30일)
idan
idan 2022년 7월 8일
댓글: Steven Lord 2022년 7월 8일
hello,
I would like to know how I create a vector with random and integers 25 digit using round and randn?
Thanks.

채택된 답변

Karim
Karim 2022년 7월 8일
RandomDouble = rand(25,1) % i.e. pick 25 random values between 0 and 1
RandomDouble = 25×1
0.2261 0.1115 0.6008 0.0399 0.7629 0.1976 0.1520 0.7056 0.1548 0.8280
RandomIntegers = randi(1000,25,1) % i.e. pick 25 integers between 1 and 1000
RandomIntegers = 25×1
543 552 914 309 791 211 947 842 821 615
  댓글 수: 1
idan
idan 2022년 7월 8일
Thanks.

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

추가 답변(1개)

Voss
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);
1.0e+18 * 5.975211767544413 3.355820591482017 2.308621702816259 6.853048767863059 7.175091024278929
sprintf('%19d\n',numbers)
ans =
'5975211767544413184 3355820591482017280 2308621702816258560 6853048767863058432 7175091024278929408 '
  댓글 수: 1
Steven Lord
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]
digits = 1×19
8 9 1 9 6 0 2 5 9 9 1 9 9 4 8 1 4 9 7
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)
ans = 1×3
9 6 0
Anyway, let's look at the number you created.
theNumber = polyval(digits, 10) % Another way to turn digits into a number
theNumber = 8.9196e+18
fromDouble = sprintf('%19d', theNumber)
fromDouble = '8919602599199481856'
Is it larger than flintmax? Yes.
isLargerThanFlintmax = theNumber > flintmax
isLargerThanFlintmax = logical
1
Let's convert the numeric digits into the corresponding characters and compare.
fromDigits = sprintf('%s', char(digits + '0'))
fromDigits = '8919602599199481497'
Do they match?
[fromDouble; fromDigits]
ans = 2×19 char array
'8919602599199481856' '8919602599199481497'
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)
distance = 1024
So adding something less than that distance to theNumber doesn't "get over the hump" to the next largest number.
isequal(theNumber, theNumber + 400)
ans = logical
1

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

태그

Community Treasure Hunt

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

Start Hunting!

Translated by