Math is a large topic to cover in any programming language so I’ve decided to call this an introduction to math, just to keep things simple. Using basic math functions is important in python because there are functions that are available to you right out of the box in python and you can avoid the overhead of having to install and import large complex libraries.
If you’ve started writing python already, you’ve probably noticed already that simple arithmatic can be performed in python just like in most programming languages. For instance, any of the following statements are valid in python:
a = 1 b = 2 a + b a * b a / b a - b
Chances are that if you’re looking to get more out python’s math function you’re probably planning on doing more than just adding and subtracting integers. Consider the following code snippet:
Start Your Freelance Career Today – Click Here To Find Out How
import math # Start Values a = 1 b = 2 f = 10 l = [1,2,3,4,5,6,7] num1 = 4.6 num2 = 5.4 num3 = 4 # Calculate f factorial print(math.factorial(f)) # Get the ceiling of 4.6 print(math.ceil(a)) # Get the floor of 5.4 print(math.floor(b)) # Find the sum of every number in list l print(math.fsum(l)) # Return E raised to the power of a. Same as math.e ** x print(math.exp(a)) # Return the natural log of a print(math.log(a)) # Return a raised to the power of b print(math.pow(a,b)) # Return the square root of 4 print(math.sqrt(num3)) # Return basic Trigometric values(argument in radians .10) # Although you can easily convert between radians and degress using # math.radians(degrees) # math.degrees(radians) print(math.tan(.10)) print(math.cos(.10)) print(math.sin(.10)) # Gimmee some pie print(math.pi) # Math constant 3 print(math.e)
There are a lot of interesting extensions to the math module in python, especially in the statistics and probability space. But because this is only an introduction, we will leave it at this.
I hope this short example was helpful. If you’d like to see the full documentation of what the math module can do in python, click here.