Reputation: 303
I'm trying to create a random generator that takes a double value and outputs a new number that is either 30% over or under the input?
var result = 4 + random.NextDouble(); //output 4.2324355
var OverOrUnder = result + or - 20%
//Output to 1 decimal place
Console.WriteLine(OverOrUnder)
Also how can I print the result so that it's only printing to 1 decimal place
Upvotes: 0
Views: 108
Reputation: 81543
Maybe
public static Random r = new Random();
public static double NextDouble(double value)
=> r.NextDouble() * (value * 1.3 - value * 0.7) + value * 0.7;
Or with an optional multiplier parameter and some simplifier math
public static double NextDouble(double value, double percent = 0.3)
=> r.NextDouble() * (2 * value * percent) + value * (1 - percent);
Example
for (int i = 0; i < 10; i++)
Console.WriteLine(NextDouble(100));
// Or for 1 decimal place
for (int i = 0; i < 10; i++)
Console.WriteLine($"{NextDouble(100):N1}"))
Output
102.433669200369
83.64005585836249
116.86387416294957
88.28468969011898
77.75586905319051
83.67046313996914
115.69185544070407
104.68552079735582
122.76178736833938
82.53277266981675
...
78.9
108.2
72.4
91.4
87.7
116.1
96.4
124.8
120.5
101.0
Upvotes: 4
Reputation: 17400
If the 30% is fixed and just the sign is random you can try like this. random.NextInt(2)
will generate either 0
or 1
. And based on that it will multiply the input
with either 0.7
(ie -30%) or 1.3
(ie +30%)
static void Main(string[] args)
{
double input = 27.34;
var random = new Random();
var newvalue = input * (random.NextInt(2) == 0 ? 0.7 : 1.3);
Console.WriteLine(newvalue.ToString("0.0"));
}
For formatting a double to your needs, see the docs of double.ToString() and either use a fixed format or a custom format for your needs.
Upvotes: 0
Reputation: 68
I hope this will work
static void Main(string[] args)
{
double input = double.Parse(Console.ReadLine());
var random = new Random();
var overOrUnder = input + (random.NextDouble() - 0.5) * input * 0.3 * 2;
Console.WriteLine($"{overOrUnder.ToString("0.0")}");
}
Upvotes: 0
Reputation: 7
Random random = new Random();
var result = input + (random.NextDouble() - 0.5) * input * 0.3 * 2;
//To print upto 1 decimal point
Console.Write(string.Format("{0:0.0}",Math.Truncate(result*10)/10));
Upvotes: 0