开发者

Random number in C

I'm writing my own method to generate a random number with C as follows:

int randomNumber(){  
    int catch = *pCOUNTER;  
    int temp = catch;  
    temp /= 10;  
    temp *= 10;  
    return (catch - temp);  
}

pCounter is basically a pointer to a register in the device I'm using. The number in that register is always increasing so my idea is to take the first digit only.

At s开发者_StackOverflow中文版ome point, the number returned becomes larger than 9 and I'm not sure if the problem is in my code or the device itself. The device is an Altera DE1 board.

Can anyone please help with that?

Thanks!


Did you declare pCounter as volatile?

volatile unsigned *pCounter = (unsigned *)0xBADDECAF;

int randomNumber(){
    return *pCounter % 10;
}


To achieve what you're trying to do in your code:

int catch = *pCOUNTER;
return (catch % 10); // Returns only the ones digit

However, I question if this approach is anywhere close to being reasonably random...


Are you sure you're not looking to use %= instead of /= & *=?


I suspect that your problem might be an 'optimization' introduced by the compiler - if you don't have pCOUNTER declared with the correct volatility, the compiler could be reading through the pointer more than once. I have no idea how many registers your processor might have - if there's not enough to hold catch in a register, it might read it multiple times (once to get something to do the temp calculations on, and again for the final return value).

Try the following, which should ensure that the pCOUNTER device/register is read exactly once:

int randomNumber(){  
    int catch = *(int volatile*)pCOUNTER;  
    int temp = catch;  
    temp /= 10;  
    temp *= 10;  
    return (catch - temp);  
}


If you're looking for a random digit (0-9 only), try this modification of your method.

int randomNumber(){  
    return ((*pCOUNTER) % 10);  
}

This isn't very random, though. If it's always increasing, presumably at a known rate then it's 100% predictable, not random at all.

Is the rand() function not allowed on that Altera board?

Edit:

You could always write your own PRNG. I did a Google search for "simple random number generator code", and found several simple examples. The simplest ones are along these lines:

int randomNumber()
{
    static long a = SomeSeedValue;

    a = (a * SomeNumber + AnotherNumber) % SomeLargePrimeNumber;
    return a % 65536;
}


If you want to arbitrarily limit the result to 9:

return (catch - temp)%10;

I recommend using a macro constant to abstract the '10' though, otherwise it's a magic number.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜