how to create random vector?
Show older comments
hello,
I would like to know how I create a vector with random and integers 25 digit using round and randn?
Thanks.
Accepted Answer
More Answers (1)
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 Comment
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)
Categories
Find more on Creating and Concatenating Matrices 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!