## Fun with Math – Returning plus or minus a Value

Have you ever wanted to add or subtract a number from another at random? This might come in handy when programming a robot to add randomness to otherwise predictable movement or decision making. I checked out the web to see what the math world had done to help out.

I found a cool formula:

n = n + 2f(random(1) – 0.5)

The idea is to take a number n, and add or subtract a number (f) from it to insert some randomness to the absolute number.

Ex. n = 100, f=10 yields either 110 or 90 at random. Pretty cool.

Anyway, here is the code in RobotC. for sake of example, I put the function in the main code, but plan to add it to my math extension header file in the future.

To make things more interesting, I made the factor random in the next example. Now the code returns a number between number-factor and number+factor. Pretty cool…

I suppose you could implement this as an inline macro too… Try it out and let me know if this is useful to you.