How can I get a random System.Decimal? System.Random
doesn't support it directly.
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Generic Generics in Managed C++
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
I wanted to generate "random" decimals up to 9 decimal places. My approach was to just generate a double and divide it for the decimals.
the "randomInt" is the number before the decimal place, you could just put 0. To reduce decimal points simply remove "9"s in random and "0"s in dividing
I know this is an old question, but the distribution issue Rasmus Faber described kept bothering me so I came up with the following. I have not looked in depth at the NextInt32 implementation provided by Jon Skeet and am assuming (hoping) it has the same distribution as Random.Next().
I puzzled with this for a bit. This is the best I could come up with:
Edit: As noted in the comments lo, mid and hi can never contain int.MaxValue so the complete range of Decimals isn't possible.
Here is Decimal random with Range implementation that works fine for me.
Check out the following link for ready-made implementations that should help:
MathNet.Numerics, Random Numbers and Probability Distributions
The extensive distributions are especially of interest, built on top of the Random Number Generators (MersenneTwister, etc.) directly derived from System.Random, all providing handy extension methods (e.g. NextFullRangeInt32, NextFullRangeInt64, NextDecimal, etc.). You can, of course, just use the default SystemRandomSource, which is simply System.Random embellished with the extension methods.
Oh, and you can create your RNG instances as thread safe if you need it.
Very handy indeed!
This is an old question, but for those who are just reading it, why re-invent the wheel?
EDIT: Removed old version
This is similar to Daniel's version, but will give the complete range. It also introduces a new extension method to get a random "any integer" value, which I think is handy.
Note that the distribution of decimals here is not uniform.