Get a randomized aberrancy around given value

后端 未结 4 2052
栀梦
栀梦 2021-01-27 02:30

I would like to add a kind of ripple to an array of known values of type double. I point that out because Random.Next / Random.NextDouble() behave different.

4条回答
  •  醉话见心
    2021-01-27 03:11

    Another method would be to loop through the array and perturb by percentage value. Once complete, calculate how far off the total is, and add the overage amount spread equally throughout all the numbers. Here's some sample code:

    var test = Enumerable.Repeat(40, 100).ToArray();
    var percent = 0.5d;
    
    var rand = new Random();
    var expectedTotal = test.Sum();
    var currentTotal = 0d;
    var numCount = test.Count();
    
    for (var i = 0; i < numCount; i++)
    {
        var num = test[i];
        var range = num * percent * 2;
    
        var newNum = num + (rand.NextDouble() - 0.5) * (range);
        currentTotal += newNum;
        test[i] = newNum;
    }
    
    var overage = (expectedTotal - currentTotal);
    
    for (var i = 0; i < numCount; i++)
        test[i] += overage / numCount;
    

提交回复
热议问题