MATLAB Answers

How to generate one random integer

11 views (last 30 days)
I need to generate one random integer.
I tried these codes:
X = randi(1)
X = rand(1)
However, it only gives random numbers between 0 and 1 (like 0.2567, 0.9432, etc.).
I am hoping to get a random number from negative infinity to positive infinity.
What function should I use to be able to generate one random integer?
Thanks in advance!

  0 Comments

Sign in to comment.

Accepted Answer

KSSV
KSSV on 3 Jul 2020
Edited: KSSV on 3 Jul 2020
As you cannot fix infinity, decide a huge/large number ..say 10^5 and use:
x = randi([-10^5 10^5],1)

  1 Comment

Roxanne Esguerra
Roxanne Esguerra on 3 Jul 2020
Thanks this is a great help!

Sign in to comment.

More Answers (1)

Walter Roberson
Walter Roberson on 3 Jul 2020
The following generates integers natively.
typecast(randi([0 255],1,8,'uint8'),'int64')
The range is all possible integers between -2^32 and +2^31-1
infinity cannot be generated with this setup, as infinity is not part of the integer system.
To generate integers outside of the range indicated above, you need to switch to double(), but if you do that, you only have 53 bits of precision available, and all values outside the range +/- 2^53 are integers that are multiplied by a power of 2 -- you could not, for example, generate 2^53 + 17 . By 1E50, adjacent representable values are 2^114 apart. Is that what you want to deal with?

  1 Comment

Roxanne Esguerra
Roxanne Esguerra on 3 Jul 2020
Thanks, I appreciate the help!

Sign in to comment.