Skip to content

Latest commit

 

History

History
146 lines (98 loc) · 2.89 KB

12.md

File metadata and controls

146 lines (98 loc) · 2.89 KB

pycobytes[12] := import math

99% uptime means 7 hours of outage each month.

Hey pips!

Just a quickie today, we’re going to look at the builtin math module. As part of the standard Python library, it provides access to common mathematical constants and functions. Let’s start by importing it:

import math

Now we can access its members using dot notation:

>>> math.pi
3.141592654

>>> math.e
2.718281828

Most of the functions you learn in maths are here, so there’s no need to define them yourself. What’s more, the ones Python provides are implemented with C code, which makes them blazingly faster than anything you could write in Python!

>>> math.log(2)  # defaults to base e
0.6931471805599453

>>> math.factorial(6)
720

If floating-point comparison has ever given you a headache, you’ll want isclose():

>>> t = 0.1 + 0.2
>>> t
0.30000000000000004

>>> math.isclose(t, 0.3)
True

If you’re up to anything rendering-related, like in game development, the trigonometric functions will come in handy:

>>> math.sin(0)
0

>>> math.cos(0)
1

Bear in mind these use radians – luckily, math abstracts the conversion for you:

>>> math.cos(math.radians(90))
0

And dist() will definitely be convenient for doing Pythagoras!

>>> p = (1, 3)
>>> q = (-2, —1)

# instead of this...
>>> ((q[0] - p[0]) ** 2
   + (q[1] - p[1]) ** 2) ** 0.5
5.0

# just use math!
>>> math.dist(p, q)
5.0

Something that comes up more often than you’d think is needing to extract the sign of a number. You can do this with a conditional:

def sign(x):
    return -1 if x < 0 else 1

Or with some absolute value trickery:

def sign(x):
    return abs(x) / x

But did you know there’s the copysign() function?

>>> math.copysign(1, -8)
-1

>>> math.copysign(1, 5)
1

It copies the sign of the 2nd number and applies it to the magnitude of the 1st. So of course, we could also pass in numbers others than 1:

>>> math.copysign(10, -2)
-10

>>> math.copysign(-9, 3)
9

>>> math.copysign(-5, -120)
-5

Python comes with plenty of useful libraries like math – which is why it’s often called a “batteries included” language!


Further Reading

It’s worth taking a quick glance through the docs for math – you might find a function that simplifies something you’re already doing!

For more advanced and heavyweight maths, we use the NumPy library, an external framework written in C.