05-27-2020, 02:44 AM
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 module is part of the Python standard library, and it is always available with every Python installation. However, you must import it before you can start using the functions it contains.
Now every function in the library is accessible by calling . If you want to import specific functions, use the standard syntax.
Python Math Floor
The function takes one argument – either a floator int – and returns the largest integer less than or equal to .
The 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 is 12 itself.
The 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 by defining a method.
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 function takes one argument – either a float or int – and returns the smallest integer greater than or equal to .
The 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 is 12 itself.
The 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 by defining a method.
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 operator.
To subtract two numbers, use the operator.
To multiply two numbers together, use the operator.
To divide two numbers, use the operator.
Note that this always returns a float even if the result is a whole number.
Remember 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 returns a float.
To raise a number to a certain power, use the operator.
This 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 operator in Python.
You 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. So for 3, the range of possible results is 0, 1, and 2.
Here are some more examples:
You can see that is 0. This result is the case for all multiples of 3.
One incredibly useful way to use the modulo operator is in loops if you want to do something every n-th iteration.
Here I used the modulo operator to print every time was divisible by 4 – i.e., when – and print in all other cases.
The final built-in operator is related to modulo. It performs floor division and is written as. As the name suggests, floor division is the same as normal division but always rounds the result down to the nearest whole number.
If you write as a compound fraction, you get . Floor division returns the whole number part of this fraction, in this case.
Here 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 as a compound fraction, you get . Floor division returns the whole number part of this fraction, in this case.
Here are some more examples:
Note 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.
This result is different to normal division which always returns a float.
You can perform floor division on any two numbers, but you may get surprising results if you add decimal places.
When you run, the result is because is and the floor of is .
Floor division for negative numbers works in the same way.
Recall that floor division takes the lower number and that. Thus the result of floor division for negative numbers is not the same as adding a minus sign to the result of floor division for positive numbers.
Try 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 when working with Python’s math module.
Python raises this error when you try to do something that is not mathematically possible or mathematically defined.
![[Image: image-64.png]](https://blog.finxter.com/wp-content/uploads/2020/05/image-64.png)
This is the graph of. Don’t worry if you don’t understand the code, what’s more important is the following point. You can see that log(x) tends to negative infinity as x tends to 0. Thus, it is mathematically meaningless to calculate the log of a negative number. If you try to do so, Python raises a math domain error.
Python Math Round
Rounding 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 function is not part of the math module but rather a built-in function you can access at all times.
It accepts two arguments:
The is an int or float, and is the rounding precision you want after the decimal point. The square brackets around signify that it is an optional argument. If you omit , Python rounds to the closest integer.
Here you can see that works as you would expect.
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.
This rounds to 2, as expected.
But this also rounds to 2! What is going on?
The function applies a type of rounding called ’rounding half to even’. This means that, in the event of a tie, Python rounds to the closest even number.
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 function is not perfect.
From 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, works as I described above, but you should know that it is not perfect. If you want something more precise, use the decimal module.
Python Math Pi
The math module includes some mathematical constants, one of which is π (pi).
It 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 every time you want to use it.
Python Math Sqrt
To calculate the square root of a number, use the function.
Note 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 which returns the integer square root for some integer . This result you get is the same as applying and then to the result.
If you pass numbers that have precise square roots, you get a similar result to, but the result is always an integer.
You cannot pass a float.
The function is the same as if is an integer,
Python Math Abs
The function is a built-in function that returns the absolute value of a number. The function accepts integers, floats, and complex numbers as input.
If you pass an integer or float, , it returns the non-negative value of and preserves its type. In other words, if you pass an integer, returns an integer, and if you pass a float, it returns a float.
The first example returns an int, the second returns a float, and the final example returns a float and demonstrates that always returns a positive number.
Complex numbers are made up of two parts and can be written as where and are either ints or floats. The absolute value of is defined mathematically as . Thus, the result is always positive and always a float (since taking the square root always returns a float).
Here you can see that always returns a float and that the result of is the same as .
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 which is in radians, and you want to convert it to degrees. Simply call .
Let’s look at some common examples.
First, I imported so that I could easily use it in all the functions. Then I calculated some common degree-to-radians conversions. Note that always returns a float. This result is expected as the vast majority of the time, the result of a conversion is not a whole number.
Note that, as is always the case with floating-point arithmetic, this function is not perfect.
This 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 in degrees, and you want to convert it to radians. Simply call .
Let’s look at some common examples.
One 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, call . Note that the function assumes that is in radians.
From high school math, we know that if 90 is in degrees. But here I demonstrate that you do not get 1.0 if you input 90. Instead, input , and you get the expected result. Alternatively, you can use the function to convert any angle in degrees to radians.
Let’s look at the result for.
Again, 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, call . Note that the function assumes that is in radians.
From high school math, we know that if 180 is in degrees. However, the trigonometric functions expect the angle to be in radians. So, you must either convert it to radians using the function, or enter the actual radians value, which is in this case. Both methods give you the answer -1.0 as expected.
Let’s look at the result of.
The result of should be 0.0, but instead, it is a tiny number close to 0. This is because π is an infinite decimal that cannot be represented entirely in a computer. This functionality should be fine for most cases. If you must have it equal to 0, check out this Stack Overflow answer for alternative methods you can use.
Python Math Tan
To calculate the tangent of some angle, call . Note that the function assumes that is in radians.
The results for are similar to those for and . You get the results you expect for 0.0, but once you start including , nothing is exactly what you expect. For example, is 1, but Python returns . This may not look the same, but, mathematically, they are equal). The result of should be positive infinity, but Python returns a huge number instead. This result is nice as it lets you perform calculations with without throwing loads of errors all the time.
Conclusion
There you have it; you now know how to use the most common functions in Python’s built-in module!
You can take the floor or ceiling of any number using and . You know all the essential operators, what types they return, and when. You’ve seen that Python raises a if you try to do something mathematically impossible. And you can use some essential functions and constants for scientific computing such as , converting angles from degrees to radians and using the most common trigonometric functions – sin, cos, and tan.
There 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
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)![[Image: image-64.png]](https://blog.finxter.com/wp-content/uploads/2020/05/image-64.png)
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

