TheRightLane on Coding

Basic programming math in 2 minutes

September 20, 2017

That's right! I'm gonna teach you all the math you need to know in 2 minutes! Feel free to send me the $30,000 you were going to pay some university!

SWEET!

Ok, not really, but here are the basics that you absolutely MUST know to be a working coder

What makes computer math difference

The most important thing to remember is that fixed and floating point math is different and don't work together

For example. This code won't work

    var num:Int = 3
    num += 3.5

Why?

You can't add a floating point (decimal) number to an integer. You have to be specific and tell the code what you want

This one works but probably isn't what you want

    var num:Int = 3
    num += Int(3.5)

This may be closer

    var num:Int = 3
    var floatNum = Float(num) + 3.5
    num = Int(floatNum)

Great! floating point for everyone!

Not so fast! Floating point math is slow and imprecise!

Which statement do you think will print?

var num:Float = 2000.0
var othernum:Float = num / 100000.0
var outnum:Float = 0
for i in 0..<100000 {
    outnum += othernum
}
if num == outnum {
    print("The same")
}
else {
    print("not the same")
}

If you answered "The same"...

WRONG

When I ran this code outnum ended up being 2001.33. That's because floating point numbers are approximate.

So, NEVER use a floating point when you need perfect precision (array indexes, counters, etc)

Addition, Subtraction, Multiplication, and Division

These all work the way you think they should.

Just be careful with Integer division. It is almost never the result you want.

Modulous %

Mod is incredibly common in day to day programming. It's also something that most people don't understand.

Going back to Elementary school modulus is the same as division with remainder. It is simply the remainder!

Sooooo... what's the answer

    let answer = 47 % 2

47 divided by 2 = 23 remainder 1
because 23 * 2 = 46 which is 1 less than 47

Great! Why do I care

Imagine you have a list and you want to capitalize every third item. MODULUS to the RESCUE!!

    for i in 0..<array.count {
        if i % 3 == 2 {
            array[i].uppercased()
        }
    }

Mod takes a little more thought to use but a little trial and error will see you through.

Knock 'em dead!

Lane Thompson