Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] Python Math Module [Ultimate Guide]

#1
Python Math Module [Ultimate Guide]

<div><p>Python’s <a href="https://docs.python.org/3/library/math.html">math module</a> 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:</p>
<figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-4-3 wp-has-aspect-ratio">
<div class="wp-block-embed__wrapper">
<div class="ast-oembed-container"><iframe title="Python Math Module [Ultimate Guide]" width="1333" height="1000" src="https://www.youtube.com/embed/F_4XbBVlXDg?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div>
</div>
</figure>
<p>The <code>math</code> module is part of the Python standard library, and it is always available with every <a href="https://blog.finxter.com/install-python-win/" target="_blank" rel="noreferrer noopener">Python installation</a>. However, you must import it before you can start using the functions it contains.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import math
</pre>
<p>Now every function in the <code>math</code> library is accessible by calling <code>math.function_name()</code>. If you want to import specific functions, use the standard <code>from math import function_name</code> syntax.</p>
<h2 id="Python-Math-Floor">Python Math Floor</h2>
<p>The <code>math.floor(x)</code> function takes one argument <code>x</code> – either a <a href="https://blog.finxter.com/decimal-pythons-float-trap-and-how-to-solve-it/" target="_blank" rel="noreferrer noopener">float </a>or int – and returns the largest integer less than or equal to <code>x</code>.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> math.floor(3.9845794)
3
>>> math.floor(9673.0001)
9673
>>> math.floor(12)
12
</pre>
<p>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 <code>math.floor(12)</code> is 12 itself.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> math.floor(-10.5)
-11
</pre>
<p>The floor of -10.5 is -11. This can sometimes be confusing but remember that -11 &lt; -10 &lt; -9 &lt; … &lt; -1 &lt; 0.</p>
<p>If you create custom a <a href="https://blog.finxter.com/python-attributes/" target="_blank" rel="noreferrer noopener">custom Python class</a>, you can make them work with <code>math.floor()</code> by defining a <code>__floor__()</code> method.</p>
<p><strong>Try It Yourself:</strong> Run the following interactive Python shell.</p>
<p> <iframe src="https://repl.it/@finxter/mathmodule?lite=true" scrolling="no" allowtransparency="true" allowfullscreen="true" sandbox="allow-forms allow-pointer-lock allow-popups allow-same-origin allow-scripts allow-modals" width="100%" height="1100px" frameborder="no"></iframe> </p>
<p><em><strong>Exercise</strong>: Can you figure out the output before running it?</em></p>
<h2 id="Python-Math.Ceil">Python Math.Ceil</h2>
<p>The <code>math.ceil(x)</code> function takes one argument <code>x</code> – either a float or int – and returns the smallest integer greater than or equal to <code>x</code>.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> math.ceil(3.9845794)
4
>>> math.ceil(9673.0001)
9674
>>> math.ceil(12)
12
</pre>
<p>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 <code>math.ceil(12)</code> is 12 itself.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> math.ceil(-10.5)
-10
</pre>
<p>The ceiling of -10.5 is -10. Your instinct that 10 &lt; 10.5 is correct when 10 is a positive number. But the opposite is true for negative numbers, and so -10.5 &lt; -10.</p>
<p>If you create custom a custom Python class, you can make them work with <code>math.ceil()</code> by defining a <code>__ceil__()</code> method.</p>
<h2 id="Python-Math-Operators">Python Math Operators</h2>
<p>The standard mathematical operators are not defined in the math module but rather in the syntax of Python itself.</p>
<p>To add two numbers together, use the <code>+</code> operator. </p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> 5 + 10
15</pre>
<p>To subtract two numbers, use the <code>-</code> operator.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> 5 - 10
-5</pre>
<p>To multiply two numbers together, use the <code>*</code> operator.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> 5 * 10
50</pre>
<p>To divide two numbers, use the <code>/</code> operator. </p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> 5 / 10
0.5</pre>
<p>Note that this <em>always</em> returns a float even if the result is a whole number. </p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> 10 / 5
2.0</pre>
<p>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 <code>/</code> returns a float.</p>
<p>To raise a number to a certain power, use the <code>**</code> operator. </p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> 5 ** 10
9765625</pre>
<p>This is ‘<em>five to the power of ten</em>‘ and you write it in the same order you would write this out by hand.</p>
<p>Then there are some other operators used less often in mathematics but are incredibly useful for<a href="https://blog.finxter.com/phd-students-of-computer-science-stay-in-academia-or-go-to-industry/" target="_blank" rel="noreferrer noopener"> computer science</a> and coding: modulus and floor division.</p>
<p>The modulus operator returns the remainder left when one number is divided by another. You perform this calculation with the <code>%</code> operator in Python. </p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> 13 % 3
1</pre>
<p>You should read the above line as ‘<em>13 modulo 3</em>‘, 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.</p>
<p>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.</p>
<p>If you do many ‘modulo n’ calculations, the <a href="https://blog.finxter.com/sets-in-python/" target="_blank" rel="noreferrer noopener">set </a>of possible results ranges from 0 up to and including <code>n-1</code>. So for 3, the range of possible results is 0, 1, and 2.</p>
<p>Here are some more examples:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> 14 % 3
2
>>> 15 % 3
0
>>> 16 % 3
1
</pre>
<p>You can see that <code>15 % 3</code> is 0. This result is the case for all multiples of 3.</p>
<p>One incredibly useful way to use the modulo operator is in <code>for</code> loops if you want to do something every n-th iteration. </p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">for i in range(10): if i % 4 == 0: print('Divisible by 4!!!') else: print('Not divisible by 4 Sad')
</pre>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Divisible by 4!!!
Not divisible by 4 Sad
Not divisible by 4 Sad
Not divisible by 4 Sad
Divisible by 4!!!
Not divisible by 4 Sad
Not divisible by 4 Sad
Not divisible by 4 Sad
Divisible by 4!!!
Not divisible by 4 Sad
</pre>
<p>Here I used the modulo operator to print <code>Divisible by 4!!!</code> every time <code>i</code> was divisible by 4 – i.e., when <code>i % 4 == 0</code> – and print <code>Not divisible by 4 Sad</code> in all other cases.</p>
<p>The final built-in operator is related to modulo. It performs floor division and is written as <code>//</code>. As the name suggests, floor division is the same as normal division but always rounds the result down to the nearest whole number.</p>
<p>If you write <code>13/3</code> as a compound fraction, you get <code>4 + 1/3</code>. Floor division returns the whole number part of this fraction, <code>4</code> in this case.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> 13 // 3
4
>>> 13 / 3 4.333333333333333</pre>
<p>Here I calculated<em> ‘thirteen floor three’</em>, and this returns 4. The result of<em> ‘thirteen divided by three’ </em>is 4.3333, and if you round this down, you get 4.</p>
<p>Another way to think of it is if you write <code>13/3</code> as a compound fraction, you get <code>4 + 1/3</code>. Floor division returns the whole number part of this fraction, <code>4</code> in this case.</p>
<p>Here are some more examples:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> 14 // 3
4
>>> 15 // 3
5
>>> 16 // 3
5</pre>
<p>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.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> 14.0 // 3
4.0
>>> 14 // 3.0
4.0
</pre>
<p>This result is different to normal division <code>/</code> which always returns a float.</p>
<p>You can perform floor division on any two numbers, but you may get surprising results if you add decimal places.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># 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.500875218804701
</pre>
<p>When you run <code>14 // 3.999</code>, the result is <code>3.0</code> because <code>14 / 3.999</code> is <code>3.508...</code> and the floor of <code>3.508...</code> is <code>3</code>.</p>
<p>Floor division for negative numbers works in the same way.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> -14 / 3
-4.666666666666667
>>> -14 // 3
-5
</pre>
<p>Recall that floor division takes the <em>lower</em> number and that <code>-5 &lt; -4</code>. 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.</p>
<p><strong>Try It Yourself:</strong> Run the following interactive Python shell.</p>
<p> <iframe src="https://repl.it/@finxter/mathmodule2?lite=true" scrolling="no" allowtransparency="true" allowfullscreen="true" sandbox="allow-forms allow-pointer-lock allow-popups allow-same-origin allow-scripts allow-modals" width="100%" height="1100px" frameborder="no"></iframe> </p>
<p><em><strong>Exercise</strong>: Which line does not produce output integer 42?</em></p>
<h2 id="Python-Math-Domain-Error">Python Math Domain Error</h2>
<p>You may encounter a special <code>ValueError</code> when working with Python’s math module.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">ValueError: math domain error
</pre>
<p>Python raises this error when you try to do something that is not mathematically possible or mathematically defined. </p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">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)
</pre>
<figure class="wp-block-image size-large"><img src="https://blog.finxter.com/wp-content/uploads/2020/05/image-64.png" alt="" class="wp-image-8765" srcset="https://blog.finxter.com/wp-content/uploads/2020/05/image-64.png 391w, https://blog.finxter.com/wp-content/uplo...00x214.png 300w" sizes="(max-width: 391px) 100vw, 391px" /></figure>
<p>This is the graph of <code>log(x)</code>. 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. </p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> math.log(-10)
Traceback (most recent call last): File "&lt;stdin>", line 1, in &lt;module>
ValueError: math domain error</pre>
<h2 id="Python-Math-Round">Python Math Round</h2>
<p>Rounding is more complicated than you might expect. Incorrectly rounding floats has lead to disastrous consequences. The <a href="https://en.wikipedia.org/wiki/Vancouver_Stock_Exchange">Vancouver Stock Exchange</a> 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 <em>half</em> of what it should have been!</p>
<p>The <code>round()</code> function is not part of the math module but rather a built-in function you can access at all times.</p>
<p>It accepts two arguments:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">round(number[, ndigits])
</pre>
<p>The <code>number</code> is an int or float, and <code>ndigits</code> is the rounding precision you want <em>after</em> the decimal point. The square brackets around <code>ndigits</code> signify that it is an optional argument. If you omit <code>ndigits</code>, Python rounds <code>number</code> to the closest integer.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># Closest integer
>>> round(10.237)
10
# One decimal place
>>> round(10.237, 1)
10.2
# Two decimal places
>>> round(10.237, 2)
10.24
</pre>
<p>Here you can see that <code>round()</code> works as you would expect.</p>
<p>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.</p>
<p>This algorithm works as expected; however, it is not that simple. Let’s look at rounding 1.5 and 2.5. </p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> round(1.5)
2</pre>
<p>This rounds to 2, as expected.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> round(2.5)
2</pre>
<p>But this also rounds to 2! What is going on?</p>
<p>The <code>round()</code> 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.</p>
<p>The mathematical logic underpinning it is explained <a href="https://en.wikipedia.org/wiki/Rounding">here</a>, 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 <a href="https://blog.finxter.com/python-lists/" target="_blank" rel="noreferrer noopener">collection </a>of numbers, the mean of the rounded numbers will be larger than the mean of the actual collection.</p>
<p>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 <a href="https://en.wikipedia.org/wiki/Rounding#Random-based_rounding_of_an_integer">mathematically rigorous methods</a> you can use in extreme circumstances.</p>
<p>Note that floating-point arithmetic has some <a href="https://docs.python.org/3.8/tutorial/floatingpoint.html#tut-fp-issues">inherent issues</a> that cannot be resolved. Fortunately, this is built into all <a href="https://blog.finxter.com/python-vs-go-which-language-you-should-choose/" target="_blank" rel="noreferrer noopener">programming languages</a>, mainly because computers represent <a href="https://blog.finxter.com/python-0-1-0-2-%e2%89%a0-0-3-me-%f0%9f%a4%94/" target="_blank" rel="noreferrer noopener">floats as binary numbers</a>. Some numbers that have finite floating-point representations – such as 0.1 – have infinite <a href="https://blog.finxter.com/tilde-python/">binary </a>representations – 0.0001100110011… – and vice versa. Thus, the <code>round()</code> function is not perfect. </p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># Expected 2.68 but got 2.67
>>> round(2.675, 2)
2.67</pre>
<p>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 <a href="https://docs.python.org/3/library/functions.html#round">known property</a> of the function. For the vast majority of cases, <code>round()</code> works as I described above, but you should know that it is not perfect. If you want something more precise, use the <a href="https://docs.python.org/3/library/decimal.html">decimal module</a>.</p>
<h2 id="Python-Math-Pi">Python Math Pi</h2>
<p>The math module includes some mathematical constants, one of which is π (pi). </p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> math.pi
3.141592653589793</pre>
<p>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 <code>math.</code> every time you want to use it. </p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> from math import pi
>>> pi
3.141592653589793</pre>
<h2 id="Python-Math-Sqrt">Python Math Sqrt</h2>
<p>To calculate the square root of a number, use the <code>math.sqrt(n)</code> function.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> math.sqrt(2)
1.4142135623730951
>>> math.sqrt(16)
4.0
</pre>
<p>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.</p>
<p>As of Python 3.8, there is also the function <code>math.isqrt(n)</code> which returns the integer square root for some integer <code>n</code>. This result you get is the same as applying <code>math.sqrt(n)</code> and then <code>math.floor()</code> to the result.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># Only works with Python 3.8
>>> math.isqrt(2)
1
>>> math.isqrt(16)
4
</pre>
<p>If you pass numbers that have precise square roots, you get a similar result to <code>math.sqrt()</code>, but the result is always an integer.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> math.isqrt(16.0)
Traceback (most recent call last): File "&lt;stdin>", line 1, in &lt;module>
TypeError: 'float' object cannot be interpreted as an integer
</pre>
<p>You cannot pass a float.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> math.isqrt(17)
4
>>> math.floor(math.sqrt(17))
4
</pre>
<p>The function <code>math.isqrt(n)</code> is the same as <code>math.floor(math.sqrt(n))</code> if <code>n</code> is an integer,</p>
<h2 id="Python-Math-Abs">Python Math Abs</h2>
<p>The <code>abs()</code> function is a built-in function that returns the absolute value of a number. The function accepts integers, floats, and complex numbers as input.</p>
<p>If you pass <code>abs()</code> an integer or float, <code>n</code>, it returns the non-negative value of <code>n</code> and preserves its type. In other words, if you pass an integer, <code>abs()</code> returns an integer, and if you pass a float, it returns a float.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># Int returns int
>>> abs(20)
20
# Float returns float
>>> abs(20.0)
20.0
>>> abs(-20.0)
20.0
</pre>
<p>The first example returns an int, the second returns a float, and the final example returns a float and demonstrates that <code>abs()</code> always returns a positive number.</p>
<p>Complex numbers are made up of two parts and can be written as <code>a + bj</code> where <code>a</code> and <code>b</code> are either ints or floats. The absolute value of <code>a + bj</code> is defined mathematically as <code>math.sqrt(a**2 + b**2)</code>. Thus, the result is always positive and always a float (since taking the square root always returns a float).</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> abs(3 + 4j)
5.0
>>> math.sqrt(3**2 + 4**2)
5.0
</pre>
<p>Here you can see that <code>abs()</code> always returns a float and that the result of <code>abs(a + bj)</code> is the same as <code>math.sqrt(a**2 + b**2)</code>.</p>
<h2 id="Python-Math-Random">Python Math Random</h2>
<p>To generate random numbers, you must use the <a href="https://blog.finxter.com/python-random-module/">Python random module</a> rather than the math module. That link takes you to an article I’ve written all about it.</p>
<h2 id="Python-Math-Degrees">Python Math Degrees</h2>
<p>It is important that you can quickly switch between degrees and radians, especially if you work with trigonometric functions.</p>
<p>Let’s say you have an angle <code>r</code> which is in radians, and you want to convert it to degrees. Simply call <code>math.degrees®</code>.</p>
<p>Let’s look at some common examples.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># 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.0
</pre>
<p>First, I imported <code>pi</code> so that I could easily use it in all the functions. Then I calculated some common degree-to-radians conversions. Note that <code>math.degrees()</code> 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.</p>
<p>Note that, as is always the case with floating-point arithmetic, this function is not perfect.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> math.degrees(pi/3)
59.99999999999999
</pre>
<p>This should return 60.0. But note that since <a href="https://en.wikipedia.org/wiki/0.999...">0.999… recurring equals 1</a>, it will not negatively impact your results.</p>
<h2 id="Python-Math-Radians">Python Math Radians</h2>
<p>Let’s say you have an angle <code>d</code> in degrees, and you want to convert it to radians. Simply call <code>math.radians(d)</code>.</p>
<p>Let’s look at some common examples.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> from math import pi
>>> math.radians(180)
3.141592653589793
>>> math.radians(180) == pi
True
>>> math.radians(45)
0.7853981633974483
>>> math.radians(45) == pi/4
True
</pre>
<p>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.</p>
<p>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.</p>
<h2 id="Python-Math-Sin">Python Math Sin</h2>
<p>To calculate the sine of some angle <code>r</code>, call <code>math.sin®</code>. Note that the function assumes that <code>r</code> is in radians.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> 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.0
</pre>
<p>From high school math, we know that <code>sin(90) = 1.0</code> if 90 is in degrees. But here I demonstrate that you do not get 1.0 if you input 90. Instead, input <code>pi/2</code>, and you get the expected result. Alternatively, you can use the <code>math.radians()</code> function to convert any angle in degrees to radians.</p>
<p>Let’s look at the result for <code>math.sin(pi)</code>.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> math.sin(pi)
1.2246467991473532e-16
</pre>
<p>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 <a href="https://stackoverflow.com/questions/18646477/why-is-sin180-not-zero-when-using-python-and-numpy">some methods</a> you can try, but I will not discuss them in this article for brevity.</p>
<p>Finally, note that all the values returned are floats even if Python can represent them as integers.</p>
<h2 id="Python-Math-Cos">Python Math Cos</h2>
<p>To calculate the cosine of some angle <code>r</code>, call <code>math.cos®</code>. Note that the function assumes that <code>r</code> is in radians.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> 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.0
</pre>
<p>From high school math, we know that <code>cos(180) = -1.0</code> 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 <code>math.radians(180)</code> function, or enter the actual radians value, which is <code>pi</code> in this case. Both methods give you the answer -1.0 as expected.</p>
<p>Let’s look at the result of <code>math.cos(pi/2)</code>.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> math.cos(pi/2)
6.123233995736766e-17
</pre>
<p>The result of <code>math.cos(pi/2)</code> 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 <a href="https://stackoverflow.com/questions/18646477/why-is-sin180-not-zero-when-using-python-and-numpy">Stack Overflow answer</a> for alternative methods you can use.</p>
<h2 id="Python-Math-Tan">Python Math Tan</h2>
<p>To calculate the tangent of some angle <code>r</code>, call <code>math.tan®</code>. Note that the function assumes that <code>r</code> is in radians.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> math.tan(0)
0.0
>>> math.tan(pi/4)
0.9999999999999999
>>> math.tan(pi/2)
1.633123935319537e+16
</pre>
<p>The results for <code>math.tan()</code> are similar to those for <code>math.sin()</code> and <code>math.cos()</code>. You get the results you expect for 0.0, but once you start including <code>pi</code>, nothing is exactly what you expect. For example, <code>tan(pi/4)</code> is 1, but Python returns <code>0.999...</code>. This may not look the same, but, mathematically, they are <a href="https://en.wikipedia.org/wiki/0.999...#Elementary_proof">equal</a>). The result of <code>tan(pi/2)</code> should be positive infinity, but Python returns a huge number instead. This result is nice as it lets you perform calculations with <code>math.tan()</code> without throwing loads of errors all the time.</p>
<h2 id="Conclusion">Conclusion</h2>
<p>There you have it; you now know how to use the most common functions in Python’s built-in <code>math</code> module!</p>
<p>You can take the floor or ceiling of any number using <code>math.floor()</code> and <code>math.ceil()</code>. You know all the essential operators, what types they return, and when. You’ve seen that Python raises a <code>Math Domain Error</code> if you try to do something mathematically impossible. And you can use some essential functions and constants for scientific computing such as <code>math.pi</code>, converting angles from degrees to radians and using the most common trigonometric functions – sin, cos, and tan.</p>
<p>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.</p>
<h2 id="Where-To-Go-From-Here?">Where To Go From Here?</h2>
<p>Do you wish you could be a programmer full-time but don’t know how to start?</p>
<p>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!</p>
<p><a href="https://tinyurl.com/become-a-python-freelancer">https://tinyurl.com/become-a-python-freelancer</a></p>
<p>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.</p>
<p>These are proven, no-BS methods that get you results fast.</p>
<p>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.</p>
<p><a href="https://tinyurl.com/become-a-python-freelancer">https://tinyurl.com/become-a-python-freelancer</a></p>
</div>


https://www.sickgaming.net/blog/2020/05/...ate-guide/
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016