Smooth Random Number Algorithm

Can someone give me a hint on how to generate "smooth" random numbers? Here is what I mean by smoothness:

Random numbers should be used in the game, for example. to direct wind and power (does anyone remember the old "worms"?). Of course, setting random numbers for these values ​​every second or so would look terribly volatile. I would prefer to have some kind of smooth fluctuations in a given range of values. It looks like a sine wave, but much more random.

Does anyone get what I need? ;-) Any ideas on how to achieve this behavior will be appreciated.

+6
source share
2 answers

If you want the delta (change) to be small, just generate a small random number for the delta.

For example, instead of:

windspeed = random (100) # 0 thru 99 inclusive 

use something like:

 windspeed = windspeed - 4 + random (9) # -4 + 0..8 gives -4..4 if windspeed > 99: windspeed = 99 if windspeed < 0: windspeed = 0 

Thus, your wind speed is still within the required boundaries, and it only gradually changes.

This will work for absolute values ​​such as speed, as well as for direction if the thing you are gradually changing is the angle from a fixed direction.

It can be well used for any measurement.


Alternatively, if you want the wind speed to change with the greatest possible delta, but slowly, you can generate the target wind speed, as you are doing now, but gradually move towards it:

 windspeed = 50 target = windspeed while true: # Only set new target if previous target reached. if target == windspeed: target = random (100) # Move gradually toward target. if target > windspeed: windspeed = windspeed + max (random (4) + 1, target - windspeed) else: windspeed = windspeed - max (random (4) + 1, target - windspeed) sleep (1) 
+4
source

Perlin (or the best simplex) noise will be the first method that comes to mind when creating smooth noise. It returns a number from 1 to -1, which adds or subtracts from the current value. You can make it less subtle or better several times ... make the smallest wind value -1 and the maximum wind value 1.

Then just set the seeder as a counter (1,2,3 ... etc.), since the input perlin / simplex will keep the values ​​"smooth".

0
source

Source: https://habr.com/ru/post/926822/


All Articles