Question

I'm tring to run an specific simulation, i have some code implemented but the result is not the one i'm expecting, i need to generate random uniform(ranged from 0 to 1) numbers with 10 decimal places (in order to convert that in other distribution). Example: 0,0345637897, 0,3445627876, 0,9776428487

this is the code:

double next = r.Next(1000000000, 9999999999);
return double.Parse(String.Format("0.{0}", next));
Was it helpful?

Solution

This should be enough:

double v = Math.Round(myRandom.NextDouble(), 10);

The difference between 0.123 and 0.1230000000 is a matter of formatting, see the answer from @SamIAm.


After the Edit:

double next = r.Next(1000000000, 9999999999);
return double.Parse(String.Format("0.{0}", next));

this is getting an integer between 1000000000 and 9999999999 and then uses the default culture to convert it to a double (in the 0 ... 1.0 range).

Since you seem to use the comma (,) as a decimal separator, at least use

return double.Parse(String.Format("0.{0}", next), CultureInfo.Invariant);

OTHER TIPS

Are you looking to pad your output? because you can do that with String.Format()

string s = String.Format({0:0000000000}, i);

you can also do it with a double or float

string s = String.Format("{0:0.0000000000}", d);

if you need a random double, just make one, and pad it with 10 decimal places when you print.

Random random = new Random();
double d = random.NextDouble()

I suggest using RNGCryptoServiceProvider. It will produces high-quality random numbers

See this post: Why use the C# class System.Random at all instead of System.Security.Cryptography.RandomNumberGenerator?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top