![]() |
|
[Tut] Python Math Module [Ultimate Guide] - Printable Version +- Sick Gaming (https://sickgaming.net) +-- Forum: Programming (https://sickgaming.net/forum-76.html) +--- Forum: Python (https://sickgaming.net/forum-83.html) +--- Thread: [Tut] Python Math Module [Ultimate Guide] (/thread-95415.html) |
[Tut] Python Math Module [Ultimate Guide] - xSicKxBot - 06-03-2020 Python Math Module [Ultimate Guide] Python’s math module provides you with some of the most popular mathematical functions you may want to use. In this article, I’ll take you through the most common ones. You can also watch the following tutorial video in which I’ll guide you through the article: The Code: mathCode: import mathNow every function in the Code: mathCode: math.function_name()Code: from math import function_namePython Math Floor The Code: math.floor(x)Code: xCode: xCode: >>> math.floor(3.9845794)
3
>>> math.floor(9673.0001)
9673
>>> math.floor(12)
12The largest numbers less than or equal to 3.9845794 and 9673.0001 are 3 and 9673, respectively. Since 12 is an integer, the result of Code: math.floor(12)Code: >>> math.floor(-10.5)
-11The floor of -10.5 is -11. This can sometimes be confusing but remember that -11 < -10 < -9 < … < -1 < 0. If you create custom a custom Python class, you can make them work with Code: math.floor()Code: __floor__()Try It Yourself: Run the following interactive Python shell. https://repl.it/@finxter/mathmodule?lite=true Exercise: Can you figure out the output before running it? Python Math.Ceil The Code: math.ceil(x)Code: xCode: xCode: >>> math.ceil(3.9845794)
4
>>> math.ceil(9673.0001)
9674
>>> math.ceil(12)
12The smallest numbers greater than or equal to 3.9845794 and 9673.0001 are 4 and 9674, respectively. Since 12 is an integer, the result of Code: math.ceil(12)Code: >>> math.ceil(-10.5)
-10The ceiling of -10.5 is -10. Your instinct that 10 < 10.5 is correct when 10 is a positive number. But the opposite is true for negative numbers, and so -10.5 < -10. If you create custom a custom Python class, you can make them work with Code: math.ceil()Code: __ceil__()Python Math Operators The standard mathematical operators are not defined in the math module but rather in the syntax of Python itself. To add two numbers together, use the Code: +Code: >>> 5 + 10
15To subtract two numbers, use the Code: -Code: >>> 5 - 10
-5To multiply two numbers together, use the Code: *Code: >>> 5 * 10
50To divide two numbers, use the Code: /Code: >>> 5 / 10
0.5Note that this always returns a float even if the result is a whole number. Code: >>> 10 / 5
2.0Remember that if you take two random numbers and divide them, it is highly unlikely they will divide each other perfectly, so it is logical that all division with Code: /To raise a number to a certain power, use the Code: **Code: >>> 5 ** 10
9765625This is ‘five to the power of ten‘ and you write it in the same order you would write this out by hand. Then there are some other operators used less often in mathematics but are incredibly useful forcomputer science and coding: modulus and floor division. The modulus operator returns the remainder left when one number is divided by another. You perform this calculation with the Code: %Code: >>> 13 % 3
1You should read the above line as ‘13 modulo 3‘, and the result is 1. This is because 3 goes into 13 four times (3 x 4 = 12) and the the total difference between 13 and 12 is: 13 – 12 = 1. Another way to think of it is if you write 13/3 as a compound fraction, you get 4 + 1/3. Looking at the fraction left over – 1/3 – take the numerator (the top part) to get the final result: 1. If you do many ‘modulo n’ calculations, the setof possible results ranges from 0 up to and including Code: n-1Here are some more examples: Code: >>> 14 % 3
2
>>> 15 % 3
0
>>> 16 % 3
1You can see that Code: 15 % 3One incredibly useful way to use the modulo operator is in Code: forCode: for i in range(10): if i % 4 == 0: print('Divisible by 4!!!') else: print('Not divisible by 4 :(')Code: Divisible by 4!!!
Not divisible by 4 :(
Not divisible by 4 :(
Not divisible by 4 :(
Divisible by 4!!!
Not divisible by 4 :(
Not divisible by 4 :(
Not divisible by 4 :(
Divisible by 4!!!
Not divisible by 4 :(Here I used the modulo operator to print Code: Divisible by 4!!!Code: iCode: i % 4 == 0Code: Not divisible by 4 :(The final built-in operator is related to modulo. It performs floor division and is written as Code: //If you write Code: 13/3Code: 4 + 1/3Code: 4Code: >>> 13 // 3
4
>>> 13 / 3 4.333333333333333Here I calculated ‘thirteen floor three’, and this returns 4. The result of ‘thirteen divided by three’ is 4.3333, and if you round this down, you get 4. Another way to think of it is if you write Code: 13/3Code: 4 + 1/3Code: 4Here are some more examples: Code: >>> 14 // 3
4
>>> 15 // 3
5
>>> 16 // 3
5Note that all of the above examples are ints being floor divided by ints. In each case, Python returns an int. But if either of the numbers is a float, Python returns a float. Code: >>> 14.0 // 3
4.0
>>> 14 // 3.0
4.0This result is different to normal division Code: /You can perform floor division on any two numbers, but you may get surprising results if you add decimal places. Code: # No difference to normal
>>> 14.999 // 3
4.0
# Returns 3.0, not 4.0!
>>> 14 // 3.999
3.0
# Now we see why
>>> 14 / 3.999
3.500875218804701When you run Code: 14 // 3.999Code: 3.0Code: 14 / 3.999Code: 3.508...Code: 3.508...Code: 3Floor division for negative numbers works in the same way. Code: >>> -14 / 3
-4.666666666666667
>>> -14 // 3
-5Recall that floor division takes the lower number and that Code: -5 < -4Try It Yourself: Run the following interactive Python shell. https://repl.it/@finxter/mathmodule2?lite=true Exercise: Which line does not produce output integer 42? Python Math Domain Error You may encounter a special Code: ValueErrorCode: ValueError: math domain errorPython raises this error when you try to do something that is not mathematically possible or mathematically defined. Code: import numpy as np
import matplotlib.pyplot as plt # Plotting y = log(x)
fig, ax = plt.subplots()
ax.set(xlim=(-5, 20), ylim=(-4, 4), title='log(x)', ylabel='y', xlabel='x')
x = np.linspace(-10, 20, num=1000)
y = np.log(x) plt.plot(x, y)![]() This is the graph of Code: log(x)Code: >>> math.log(-10)
Traceback (most recent call last): File "<stdin>", line 1, in <module>
ValueError: math domain errorRounding is more complicated than you might expect. Incorrectly rounding floats has lead to disastrous consequences. The Vancouver Stock Exchange used an overly simplified rounding algorithm when trading stocks. In less than two years, the algorithm resulted in the price of the stock exchange being half of what it should have been! The Code: round()It accepts two arguments: Code: round(number[, ndigits])The Code: numberCode: ndigitsCode: ndigitsCode: ndigitsCode: numberCode: # Closest integer
>>> round(10.237)
10
# One decimal place
>>> round(10.237, 1)
10.2
# Two decimal places
>>> round(10.237, 2)
10.24Here you can see that Code: round()First, I want to round 10.237 to an integer. So, let’s look at the first value after the decimal place and round down if it’s less than 5 and up if it’s greater than 5. The first value is 2, and so you round down to get 10. For the next example, round 10.237 to one decimal place. Look at the second decimal place – 3 – and so round it down to get 10.2. Finally, round 10.237 to two decimal places by looking at the third decimal place – 7 – and rounding up to get 10.24. This algorithm works as expected; however, it is not that simple. Let’s look at rounding 1.5 and 2.5. Code: >>> round(1.5)
2This rounds to 2, as expected. Code: >>> round(2.5)
2But this also rounds to 2! What is going on? The Code: round()The mathematical logic underpinning it is explained here, but in short, the reason Python does this is to preserve the mean of the numbers. If all the ties are rounded up (as we are taught in school), then if you round a collectionof numbers, the mean of the rounded numbers will be larger than the mean of the actual collection. Python assumes that about half will be odd for a random collection of numbers, and half will be even. In practice, this is true most of the time. However, there are more mathematically rigorous methods you can use in extreme circumstances. Note that floating-point arithmetic has some inherent issues that cannot be resolved. Fortunately, this is built into all programming languages, mainly because computers represent floats as binary numbers. Some numbers that have finite floating-point representations – such as 0.1 – have infinite binaryrepresentations – 0.0001100110011… – and vice versa. Thus, the Code: round()Code: # Expected 2.68 but got 2.67
>>> round(2.675, 2)
2.67From what I’ve said above, this example should return 2.68 as that is an even number. However, it returns 2.67. This result is not a bug and is a known property of the function. For the vast majority of cases, Code: round()Python Math Pi The math module includes some mathematical constants, one of which is π (pi). Code: >>> math.pi
3.141592653589793It is the ratio of the circumference of a circle to its diameter and is 3.141592653589793 to 15 decimal places. If you are going to use this constant a lot, I recommend importing it separately to save you typing out Code: math.Code: >>> from math import pi
>>> pi
3.141592653589793To calculate the square root of a number, use the Code: math.sqrt(n)Code: >>> math.sqrt(2)
1.4142135623730951
>>> math.sqrt(16)
4.0Note that this always returns a float. Even if you pass an int and Python can express the result as an int, it always returns a float. This functionality is similar to the division operator and makes logical sense; the vast majority of times you calculate a square root, it will not return an integer. As of Python 3.8, there is also the function Code: math.isqrt(n)Code: nCode: math.sqrt(n)Code: math.floor()Code: # Only works with Python 3.8
>>> math.isqrt(2)
1
>>> math.isqrt(16)
4If you pass numbers that have precise square roots, you get a similar result to Code: math.sqrt()Code: >>> math.isqrt(16.0)
Traceback (most recent call last): File "<stdin>", line 1, in <module>
TypeError: 'float' object cannot be interpreted as an integerYou cannot pass a float. Code: >>> math.isqrt(17)
4
>>> math.floor(math.sqrt(17))
4The function Code: math.isqrt(n)Code: math.floor(math.sqrt(n))Code: nPython Math Abs The Code: abs()If you pass Code: abs()Code: nCode: nCode: abs()Code: # Int returns int
>>> abs(20)
20
# Float returns float
>>> abs(20.0)
20.0
>>> abs(-20.0)
20.0The first example returns an int, the second returns a float, and the final example returns a float and demonstrates that Code: abs()Complex numbers are made up of two parts and can be written as Code: a + bjCode: aCode: bCode: a + bjCode: math.sqrt(a**2 + b**2)Code: >>> abs(3 + 4j)
5.0
>>> math.sqrt(3**2 + 4**2)
5.0Here you can see that Code: abs()Code: abs(a + bj)Code: math.sqrt(a**2 + b**2)Python Math Random To generate random numbers, you must use the Python random module rather than the math module. That link takes you to an article I’ve written all about it. Python Math Degrees It is important that you can quickly switch between degrees and radians, especially if you work with trigonometric functions. Let’s say you have an angle Code: rCode: math.degrees(r)Let’s look at some common examples. Code: # You need to use pi a lot, so let's import it
>>> from math import pi
>>> math.degrees(pi)
180.0
>>> math.degrees(pi/4)
45.0
>>> math.degrees(2*pi)
360.0First, I imported Code: piCode: math.degrees()Note that, as is always the case with floating-point arithmetic, this function is not perfect. Code: >>> math.degrees(pi/3)
59.99999999999999This should return 60.0. But note that since 0.999… recurring equals 1, it will not negatively impact your results. Python Math Radians Let’s say you have an angle Code: dCode: math.radians(d)Let’s look at some common examples. Code: >>> from math import pi
>>> math.radians(180)
3.141592653589793
>>> math.radians(180) == pi
True
>>> math.radians(45)
0.7853981633974483
>>> math.radians(45) == pi/4
TrueOne downside with converting degrees to radians is that radians are much harder for humans to read. So, I added in the equality statements afterward to show you that 180 degrees, when converted to radians, is π and likewise for 45 degrees and π/4. This function is especially crucial if you want to use any of the trigonometric functions as they assume you are passing an angle in radians. Python Math Sin To calculate the sine of some angle Code: rCode: math.sin(r)Code: rCode: >>> math.sin(0)
0
# Assumes angle is in radians!
>>> math.sin(90)
0.8939966636005579
# Convert to radians
>>> math.sin(math.radians(90))
1.0
# Enter as radians
>>> math.sin(pi/2)
1.0From high school math, we know that Code: sin(90) = 1.0Code: pi/2Code: math.radians()Let’s look at the result for Code: math.sin(pi)Code: >>> math.sin(pi)
1.2246467991473532e-16Again, from high school math, you expect the result to be 0.0, but, as is often the case with floating-point arithmetic, this is not the case. Although we know that the sine of 0 and π are the same value, unfortunately, it is not reflected in the output. This result is because π is an infinite decimal that cannot be represented fully in a computer. However, the number is so small that it should not make a massive difference to your calculations. But if you need it to equal 0, there are some methods you can try, but I will not discuss them in this article for brevity. Finally, note that all the values returned are floats even if Python can represent them as integers. Python Math Cos To calculate the cosine of some angle Code: rCode: math.cos(r)Code: rCode: >>> math.cos(0)
1.0
# Assumes angle is in radians
>>> math.cos(180)
-0.5984600690578581
# Convert to radians
>>> math.cos(math.radians(180))
-1.0
# Enter angle in radians
>>> math.cos(pi)
-1.0From high school math, we know that Code: cos(180) = -1.0Code: math.radians(180)Code: piLet’s look at the result of Code: math.cos(pi/2)Code: >>> math.cos(pi/2)
6.123233995736766e-17The result of Code: math.cos(pi/2)Python Math Tan To calculate the tangent of some angle Code: rCode: math.tan(r)Code: rCode: >>> math.tan(0)
0.0
>>> math.tan(pi/4)
0.9999999999999999
>>> math.tan(pi/2)
1.633123935319537e+16The results for Code: math.tan()Code: math.sin()Code: math.cos()Code: piCode: tan(pi/4)Code: 0.999...Code: tan(pi/2)Code: math.tan()Conclusion There you have it; you now know how to use the most common functions in Python’s built-in Code: mathYou can take the floor or ceiling of any number using Code: math.floor()Code: math.ceil()Code: Math Domain ErrorCode: math.piThere are some more functions I didn’t get the chance to cover in this article, such as the inverse and hyperbolic trigonometric functions. With your knowledge, you’ll easily understand and use them if you quickly read the docs. Where To Go From Here? Do you wish you could be a programmer full-time but don’t know how to start? Check out the pure value-packed webinar where Chris – creator of Finxter.com – teaches you to become a Python freelancer in 60 days or your money back! https://tinyurl.com/become-a-python-freelancer It doesn’t matter if you’re a Python novice or Python pro. If you are not making six figures/year with Python right now, you will learn something from this webinar. These are proven, no-BS methods that get you results fast. This webinar won’t be online forever. Click the link below before the seats fill up and learn how to become a Python freelancer, guaranteed. https://tinyurl.com/become-a-python-freelancer |