Home > Software engineering >  Limit range, set the average, random number
Limit range, set the average, random number

Time:11-01

Numerical range a, b, set a value between a and b, c set numerical number x, survival as a random number x value
Score is not much, I hope you can provide the train of thought

CodePudding user response:

You mean is to generate a random number between a to b x?

CodePudding user response:

Through thinking, can convert model, namely known numerical range [a, b], set x number of numerical summation to Sum,
Premise condition is the Sum of the range should be [a * x, b * x]
So first determines to take the first value, the x1 numerical range?
Assume that x - 1 values for a, the x1's range Sum - a * (x - 1), and have limited ceiling to b, then the Max (x1)=Min (b, Sum - a * (x - 1))
Similarly, assume that x - 1 numerical is b, the x1's lower limit value is the Sum - b * (x - 1), and have limited ceiling to b, then the Min (x1)=Max (a, Sum - b * (x - 1))
The x1 in [Max (a, Sum - b * (x - 1)), Min (b, Sum - a * (1) x)] within the scope of value, is to choose the x2, Sum1=Sum - x1,
The selection in the case of a value, I also rest (x - I) to choose the numerical, Sum (I)=Sum (x1 + x2 +... ) + x (I - 1), x (I) the scope should be [Max (a, the Sum of (I) - b * (x - I)), Min (b, Sum (I) - a * (x - I))], you can use looping statements to x (I) assignment, the code is as follows:
As a Double Private Sub XArr (a, b, as a Double Sum as Double, N as Interge)
Dim X () as a Double
Redim X (1 to N)
For I=1 to N
X (I)=RndBT (Max (a, the Sum of (I) - b * (N - I)), Min (b, Sum (I) - a * (N - I)), the Index) 'RndBT is a custom function, a random number between two numerical
Sum=Sum - X (I)
Next
End Sub
Pure hand to play, have a wrong place please understand
If you have better ideas or code I will still give points
  • Related