Maths

../_images/python-math2.png

You can do mathematical operations, manipulate numbers and generate random numbers in python.

Basic Maths

Mathematical operators

You can use numeric values or variables with the basic arithmetic operators: +,-,*,/ in the same way as you would with a calculator.

Here is the lists of mathematical operations that you can do in python:

Mathematical Operations
Addition a = 22 + 7 Add 2 or more numbers
Subtraction a = 22 - 7 Subtract 2 or more numbers
Multiplication a = 22 * 7 Multiply 2 or more numbers
Division a = 22 / 7 Divide a number by another number
Exponent a = 2 ** 8 Raise a number by an exponent
Modulo hour = 15 % 12 Get the remainder of the division of 2 numbers
Floor Division a = 10 // 6 Get the integer part of the division of 2 numbers

Random numbers

We can generate a random integer in a given range. The random.randint() function will allow us to do that.

You must add import random near the start of your program. This will show a random number between 1 and 6:

import random

display.show(random.randint(1, 6))

You can use random.choice() to pick a random item from a list:

import random

hands = ['rock', 'paper', 'scissors']
display.scroll(random.choice(hands))

Precedence

Mathematical operations are not calculated in order from left to right. Some operations take precedence over others. In Python, operations are carried out in this order:

  • Brackets (parentheses) ()
  • Exponentials (raise to the power of) **
  • Multiplication *, division /, modulo (remainder) %, floor division //
  • Addition + and subtraction -

Absolute

The abs() function will turn any number, positive or negative into a positive number.

display.scroll(abs(accelerometer.get_y()))

This is useful if you are only interested in the strength of accelerometer or compass strength readings which can be positive or negative.

This will show the magnitude of the accelerometer reading in the Y-axis as a positive number, regardless of whether the reading was positive or negative.

Rounding

this rounds off a number to an integer or a given decimal place.

integer

this rounds off to the nearest integer:

display.scroll(int(4.9))

decimal place

this rounds off to the nearest decimal place indicated (2 in this example):

display.scroll(round(2.317,2))

floor

this rounds off to the current integer, eliminating the decimal places (from 2.9 to 2):

from math import floor

display.scroll(floor(2.9))

ceiling

this rounds off to the next integer, increasing it by 1 (from 2.1 to 3):

from math import ceil

display.scroll(ceil(2.1))

Advanced Maths

Using from math import * at the start of your program gives you access to some advanced mathematical functions.

Constants

Mathematical constants π (pi) and e (base of natural logarithm) can be used.

from math import *

display.scroll(pi)

Pi will be shown as 3.141593

from math import *

display.scroll(e)

e will be shown as 2.718282

Square root

Use sqrt() to calculate the square root of a number.

from math import *

display.scroll(sqrt(25))

Trigonometric functions

You can use the trigonometric functions like cos, sin, tan, acos, asin, atan.

from math import *

display.scroll(cos(1))

Convert degrees and radians

degrees to radians:

from math import *

display.scroll(radians(180))

radians to degrees:

from math import *

display.scroll(degrees(3))

Logarithms

To show 10 to base 2:

from math import *

display.scroll(log(10, 2))

Binary and Hexadecimal numbers

Python has some useful ways of representing and converting binary and hexadecimal numbers. These do not need import math

Binary numbers are represented with 0b at the start:

number = 0b11111111
display.scroll(number)

The example above displays 255, the base 10 (denary) equivalent of binary 11111111.

Use bin() to convert a number to a binary string representation:

display.scroll(bin(255))

This shows base 10 (denary) 255 as a binary string '0b11111111'.

Hexadecimal numbers are represented with 0x at the start:

number = 0xFF
display.scroll(number)

Bitwise operators

Bitwise operators allow you to perform operations on numbers at the bit, or binary, level.

bitwise and

The and operator & output of any given digit will be 1 if both digits are 1. This example will mask out the the last (least significant) 4 bits and only keep the first (most significant) 4 bits of y. It will display 0b1010000.

x = 0b11110000
y = 0b10101010
display.scroll(bin(x & y))

bitwise or

The or operator | will output a 1 if either digit is 1.

x = 0b11110000
y = 0b10101010
display.scroll(bin(x | y))

You can also use other bitwise operations like exclusive or, shift left, shift right and complement.

Exercises

  1. Try to use the mathematical operations to divide 100 by 7 and then round off using floor.
  2. Try to use the other ways of rounding off a number as well.
  3. Generate 20 random numbers and store it in a list, then determine if the number is a prime number or not.