how to create random vector?
122 ビュー (過去 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)
参考
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!