# 为什么这个伪随机数发生器（LFSR）的输出是如此可预测的？[英] Why are the outputs of this pseudo random number generator (LFSR) so predictable?

### 问题描述

```    module LFSR(
input clock,
input reset,
output [12:0] rnd
);

wire feedback = rnd[12] ^ rnd[3] ^ rnd[2] ^ rnd[0];

reg [12:0] random;

always @ (posedge clock or posedge reset)
begin
if (reset)
random <= 13'hF; //An LFSR cannot have an all 0 state, thus reset to FF
else
random <= {random[11:0], feedback}; //shift left the xor'd every posedge clock
end

assign rnd = random;

endmodule
```

## 推荐答案

lfsr仅生成一个每个时钟随机位.它不会在每个周期生成新的(在您的情况下)13位数字. rnd中的其他12位只是旧的随机值，因此它不会看起来很随机.

## 其他推荐答案

### 问题描述

Recently I asked here, how to generate random numbers in hardware and was told to use an LFSR. It will be random but will start repeating after a certain value.

The problem is that the random numbers generated are so predictable that the next value can be easily guessed. For example check the simulation below:

The next "random" number can be guessed by adding the previous number with a +1 of itself. Can someone please verify if this is normal and to be expected.

Here is the code I used for the LFSR:

```    module LFSR(
input clock,
input reset,
output [12:0] rnd
);

wire feedback = rnd[12] ^ rnd[3] ^ rnd[2] ^ rnd[0];

reg [12:0] random;

always @ (posedge clock or posedge reset)
begin
if (reset)
random <= 13'hF; //An LFSR cannot have an all 0 state, thus reset to FF
else
random <= {random[11:0], feedback}; //shift left the xor'd every posedge clock
end

assign rnd = random;

endmodule
```

The location of the bits to XOR are picked up from here: The table page 5

## 推荐答案

LFSR only generates one random bit per clock. It doesn't generate a new (in your case) 13-bit number each cycle. The other 12 bits in rnd are just the old random values, so it will not appear very random.

If you need a 13-bit random number, then you must either sample LFSR every 13 cycles, or put 13 LFSR in parallel with different seeds, and use the 13 zero bits as your random number.

## 其他推荐答案

An LFSR is most certainly not 'random' in any real sense whatsoever. To quote Von Neumann "Any one who considers arithmetical methods of producing random digits is, of course, in a state of sin." I haven't looked up whether the feedback terms you've chosen are maximal, meaning that they'll provide a sequence with a length equal to the number of bits in your LFSR, but that's the best you can do.

So yes, the next value in your LFSR is extremely predictable. If you need something more securely 'random' you need to look into cryptographic methods, these depend on a secret key of course, and are also much more computationally intensive than an LFSR. You 'get what you pay for' though.

Incidentally, a system where you get predictable 'random' numbers is highly useful in it's own right. Usually for simulation purposes.