Home > Information, RobotC Code > Fun with Math – Returning plus or minus a Value

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.

 math11

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…

math1

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

Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: