WEEK: 6
Active: February 14th - February 20th
Work Due: February 21st @ 9:00AM

Basic Math Operators in p5

Last week we began to look at how we could use math to transform our sketches. Right now, we are going to dive down that path way a little further, reminding ourselves about various math operators and order of operation.

For some of you this may have been panic inducing, but do not fear, this is the “real world” application of math you always asked your teachers about. It is time to use math to make cool things. Also, there is no way out of using math, a huge chunk of coding is figuring out how to mathematically represent what it is you want to do.

Addition / Subtraction

The most basic type of math that you will do, is obviously addition and subtraction. This is essentially the adding of numbers together.

To add or subtract, we use the addition or subtraction operators.

JavaScript operators are used to assign values, compare values, perform arithmetic operations, and more.

Arithmetic operators are used to perform arithmetic between variables and/or values.

In JavaScript, or any language for that matter, an operator tells the computer what to do with values on either side of it. The addition operator is the plus character ( + ), you are used to seeing throughout your life. Likewise, the subtraction operator, is the minus character ( - ). We can pass raw Numbers, variables holding Numbers, or strings (more on this last one later) to the addition operator. We can pass Numbers or variables holding Numbers to the subtraction operator.

Addition Operator Examples
// declare a variables to hold result values
var result;
// add two numbers together, and store it in a variable
// 'result' will be 13
result = 10 + 3;

// declare and set two variables
var foo = 5;
var bar = 4;
// add to numbers stored in variables together
// 'result' will be 9.
result = foo + bar;
Subtraction Operator Examples
// declare a variables to hold result values
var result;
// add two numbers together, and store it in a variable
// 'result' will be 7
result = 10 - 3;

// declare and set two variables
var foo = 5;
var bar = 4;
// add to numbers stored in variables together
// 'result' will be 1.
result = foo - bar;

As we saw last week, we can also store the results of an arithmetic operation back into a variable used in the statement.

Overwriting Variables
// declare a variables to hold result values, initialize this value to 2.
var value = 2;
// add two numbers together
// Store the result back in 'value'
// 'value' will be 5
value = value + 3;

// 'value' will be 4
value = value - 1;

Multiplication

The multiplication operator is the asterisk character ( * ). This character is typically located on the same key as the number ‘8’, or is the top-right key on a numpad area. As with the addition and subtraction operators, this operator expects Numbers on either side. These numbers are then multiplied together.

Multiplication Operator Examples
// declare a variables to hold result values
var result;
// add two numbers together, and store it in a variable
// 'result' will be 30
result = 10 * 3;

// declare and set two variables
var foo = 5;
var bar = 4;
// add to numbers stored in variables together
// 'result' will be 20.
result = foo * bar;

Division

Just as subtraction is the counterpart to addition, division is the counterpart to multiplication. In JavaScript, the division operator is the forward-slash character ( / ).

Division Operator Examples
// declare a variables to hold result values
var result;
// add two numbers together, and store it in a variable
// 'result' will be 5
result = 10 / 2;

// declare and set a variable
var bar = 2;
// add to numbers stored in variables together
// 'result' will be 2.5.
result = result / bar;

Dividing by 0

You likely remember your teachers trying to impress upon you the importance that you cannot divide by 0. This is especially true in programming. If you create a statement that asks the computer to divide by 0, then the computer will return results that will likely crash your program later on.

There are two possible values in JavaScript with the denominator (the bottom number, of the one we “divide by”) is set to 0. If the numerator (the top number) is any number, expect ‘0’, the result will be infinity.

Divide by 0
var result;
result = 1 / 0;
// results in infinity
console.log( result );

If you then, try and pass this result to another function as a parameter, the program will fail “silently”. This means it will try and do what you have asked, but will be unable to. Since it does not know what you mean, that part of your sketch will not be there, and you will be left with no information as to why things are not working as expected. Unlike some problems in coding, this will also not stop the execution of your sketch, so you will be left, potentially not know why or where things went amiss.


If the numerator is also set to 0, the program will instead return the value NaN. This stands for “Not a Number”. This will cause similar problems to the example above.

Divide by 0
var result;
result = 0 / 0;
// results in infinity
console.log( result );

Regardless of which technical result you get, the end result will be the same, and you will have problems with your code sketch. So…DO NOT DIVIDE BY 0.


This will only really be an issue when you are passing a variable to a divide operator, if this variable has any chance of being 0.

One way to solve this problem and avoid Infinity values or NaN values, is to set your problems and variables up for multiplication instead. For example, instead of dividing something by 2, you could multiple it by 0.5. So, if you can setup your code to allow for multiplication instead, you are less likely to get unexpected results.

Modulo ( % )

One arithmetic operator that is likely unfamiliar is the modulo (sometimes known as modulus) operator, which calculates the remainder of a quotient after division. Modulo is represented by a percentage sign ( % ).

For example, we know that 3 goes into 6 exactly twice, so there would be no remainder. This could also be written as;

  • 6 ÷ 3 = 2r0

Conversely, if we divide 7 by 3, we know that 3 goes into 7 twice. This leave us with a remainder of 1.

  • 2 * 3 = 6
  • 7 - 6 = 1

So…

  • 7 ÷ 3 = 2r1

The modulus operator will return only the left over of these two calculations. So, if we say “6 modulo 3”, the result will be the remainder, or ‘0’. Likewise, if we calculate “7 modulo 3”, the result will be the remainder, or ‘1’.

  • 6 % 3 = 0
  • 7 % 3 = 1

This pattern will continue if we increment the numerator (‘7’) to ‘8’. The value 2 goes into 8 twice, with a remainder of 2.

  • 8 ÷ 3 = 2r2
  • 8 % 3 = 2

If the numerator is incremented again to ‘9’, the result of the modulus operator will be ‘0’. This is because ‘3’ goes into ‘9’ exactly 3 times without a remainder.

  • 9 ÷ 3 = 3r0
  • 9 % 3 = 0


The modulus operator is a very powerful arithmetic operator, and one you need to be comfortable with (you will be asked to use it multiple times in your homework assignment this week).

The modulus operator is often used to keep values “within” bounds. For example, the following code, has a regularly incrementing value (numerator), which we will modulo by 3. This means the result will always be; 0, 1, or 2. The numerator’s value, and the result of the modulo operator are both displayed as the sketch progresses.

sketch.js
function setup() {
    // createCanvas( windowWidth, windowHeight );
    createCanvas( windowWidth, 600 );
    // reduce the frame rate, so we can see the changes
    frameRate(3);
}

// declare a variable, 'numerator'
// instantiate the variable to '0'
var numerator = 0;

function draw() {
    background( 'rgb(63, 186, 218)' );
    textSize(24);

    // calculate the result
    var result = numerator % 3;

    // display the equation and result
    text( numerator + " % 3 = " + result, 20, 80 );

    // increment the numerator
    numerator = numerator + 1;
}
[ Code Download ] [ View on GitHub ] [ Live Example ]

Since the modulo operator can be used to keep results “within bounds”, we can also use this operator to keep a numerator “bounded”. This can be accomplished by assigning the results of an operation back to the variable. For example, in the following code, we increment a variable by ‘1’ and modulo by ‘3’ every frame. This keeps the variable bound between ‘0’-‘2’, as it can result in ‘3’.

var value = 0;

function draw() {
    value = (value + 1) % 3;
}
[ Code Download ] [ View on GitHub ] [ Live Example ]

This same logic can be used to bound an ellipse, that moves from left-to-right within a canvas. If we update the position of an ellipse every frame, but also modulo it by the width of the canvas, then we are guaranteed that it stays within the canvas.

sketch.js
// declare and instantiate 'pos_x'
// This will represent the position of an ellipse
var pos_x = 20;

function draw() {
        // draw an ellipse at pos_x
    ellipse( pos_x, 140, 30 );

    // update the ellipses position
    pos_x = pos_x + 5;
    // bound it to the width of the canvas
    pos_x = pos_x % width;
}
[ Code Download ] [ View on GitHub ] [ Live Example ]

Exponentiation

The exponentiation operator calculates the power of a number by its exponent. This operator is two asterisks placed together ( ** ).

So, 2-squared or “2 to the power of 2”;

  • 22

Would be written as;

var result = 2 ** 2;

Which, of course would equal ‘4’.


If you do not like the two-asterisks operator, you can instead use the exponential function pow(n,e). Where the input parameter n is the base number, and e is the exponent or “power by which to raise the base”.


This operator allows us to calculate the value of any Number to the power of any other Number. (NOTE: This following demonstrates both the operator and function)

var exponent = 0;

function draw() {
    var operator_result = 2 ** exponent;
    var func_result = pow( 2, exponent );
    exponent = exponent + 1;
}
[ Code Download ] [ View on GitHub ] [ Live Example ]

Increment & Decrement

Another useful set of operators are the increment and decrement operators. Increment and decrement operators increase or reduce the numerical value of a variable by one. They are represented by two plus signs ( ++ ) or two minus signs ( -- ), and are often used with loops.

These operators take the value of a variable, increment it by ‘1’, and then reassign the value back to the variable.

Note: You can only use these operators with variables, not raw Numbers. Doing so will thrown a “reference error”.

The following results in constantly incrementing and decreasing values, respectively.

Note: We do not have to “reassign” the value back to its variable.

var inc_val = 0;
var dec_val = 100;

function draw() {
    inc_val++;
    dec_val--;
}
[ Code Download ] [ View on GitHub ] [ Live Example ]

Unary Operators

Another operator that you will use from time to time is the “unary negation” operator. This operator is a negative character ( - ), prepended (“added to the front”) to a Number or variable.

More simply stated, to create a negative number, use the “unary negation” operator.

// specify a negative number
var value = -20;

This operator can also be used with variables, to negate their current value.

var value = 13;

// return the negative of the variables value
var new_val = -value;

NOTE: If you negate a negative number, it returns a positive.

var value = -4;

// return the negative of the variables value
// IN THIS CASE, THIS RESULTS IN +4
var new_val = -value;

There is also a “positive unary” operator ( + i.e. +4). But it is only used in special circumstances, that we will discuss later.

Additional Assignment Operators

There are a number of additional assignment operators you should also be aware of. These operators all take a variable, perform some basic arithmetic on the variable (addition/subtraction, multiplication/division, modulo, or exponentiation), and then assign the new value back to the variable.

These operators are written by appending an equals character ( = ), to an existing arithmetic operator. They are as follows;

  • += addition assignment operator
  • -= subtraction assignment operator
  • *= multiplication assignment operator
  • /= division assignment operator
  • %= modulus assignment operator
  • **= exponentiation assignment operator

For example, let’s add ‘2’ to the value of a variable and store it back in the same variable name space. The following are equivalent, and demonstrate the old-long way of doing this, and the new-shorter way, using the new operator. The following will both accomplish the same task.

var value = 0;

// old way
value = value + 2;

// new way
value += 2;

Previous section:
Next section: