What is math module in Python?
In this course, you’ll learn all about Python’s Show
For straightforward mathematical calculations in Python, you can use the built-in mathematical
operators, such as addition ( Fortunately, no. Python provides a module specifically designed for higher-level
mathematical operations: the By the end of this course, you’ll learn:
A background in mathematics will be helpful here, but don’t worry if math isn’t your strong suit. This course will explain the basics of everything you need to know. For more information on concepts covered in this lesson, you can check out:
Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Exploring the Python math Module In this article, you’ll learn all about Python’s For straightforward mathematical calculations in Python, you can use the built-in mathematical operators, such as addition ( Fortunately, no. Python provides a module specifically designed for higher-level mathematical operations: the By the end of this article, you’ll learn:
A background in mathematics will be helpful here, but don’t worry if math isn’t your strong suit. This article will explain the basics of everything you need to know. So let’s get started! Getting to Know the Python math ModuleThe Python The Python
Since the You can import the Python Constants of the math ModuleThe Python
In this section, you’ll learn about the constants and how to use them in your Python code. PiPi (π) is the ratio of a circle’s circumference (c) to its diameter (d):
This ratio is always the same for any circle. Pi is an irrational number, which means it can’t be expressed as a simple fraction. Therefore, pi has an infinite number of decimal places, but it can be approximated as 22/7, or 3.141. You can access pi as follows: >>>
As
you can see, the pi value is given to fifteen decimal places in Python. The number of digits provided depends on the underlying C compiler. Python prints the first fifteen digits by default, and So what are some of the ways that pi can be useful to you? You can calculate the circumference of a circle using 2πr, where r is the radius of the circle: >>>
You can use >>>
You can use TauTau (τ) is the ratio of a circle’s circumference to its radius. This constant is equal to 2π, or roughly 6.28. Like pi, tau is an irrational number because it’s just pi times two. Many mathematical expressions use 2π, and using tau instead can help simplify your equations. For example, instead of calculating the circumference of a circle with 2πr, we can substitute tau and use the simpler equation τr. The use of tau as the circle constant, however, is still under debate. You have the freedom to use either 2π or τ as necessary. You can use tau as below: >>>
Like >>>
You can use Euler’s NumberEuler’s number (e) is a constant that is the base of the natural logarithm, a mathematical function that is commonly used to calculate rates of growth or decay. As with pi and tau, Euler’s number is an irrational number with infinite decimal places. The value of e is often approximated as 2.718. Euler’s number is an important constant because it has many practical uses, such as calculating population growth over time or determining rates of radioactive
decay. You can access Euler’s number from the >>>
As with InfinityInfinity can’t be defined by a number. Rather, it’s a mathematical concept representing something that is never-ending or boundless. Infinity can go in either direction, positive or negative. You can use infinity in algorithms when you want to compare a given value to an absolute maximum or minimum value. The values of positive and negative infinity in Python are as follows: >>>
Infinity is not a numerical value. Instead, it’s
defined as >>>
Both >>>
In the above code, Similarly, >>>
Negative infinity is smaller than the value of >>>
As you can see, neither addition nor division changes the value of Not a Number (NaN)Not a number, or NaN, isn’t really a mathematical concept. It originated in the computer science field as a reference to values that are not numeric. A NaN value can be due to invalid inputs, or it can indicate that a variable that should be numerical has been corrupted by text characters or symbols. It’s always a best practice to check if a value is NaN. If it is, then it could lead to invalid values in your program. Python introduced the NaN constant in version 3.5. You can observe the value of NaN is not a numerical value. You can
see that the value of Arithmetic FunctionsNumber theory is a branch of pure mathematics, which is the study of natural numbers. Number theory usually deals with positive whole numbers or integers. The Python
Find Factorials With Python factorial()You may have seen mathematical expressions like 7! or 4! before. The exclamation marks don’t mean that the numbers are excited. Rather, “!” is the factorial symbol. Factorials are used in finding permutations or combinations. You can determine the factorial of a number by multiplying all whole numbers from the chosen number down to 1. The following table shows the factorial values for 4, 6, and 7:
You can see from the table that 4!, or four factorial, gives the value 24 by multiplying the range of whole numbers from 4 to 1. Similarly, 6! and 7! give the values 720 and 5040, respectively. You can implement a factorial function in Python using one of several tools:
First you are going to look at a factorial implementation using a
You can also use a recursive function to find the factorial. This is more complicated but also more elegant than using a
The following example illustrates
how you can use the >>>
Even though their implementations are different, their return values are the same. However, implementing functions of your own just to get the factorial of a number is time consuming and inefficient. A better method is to use >>>
This approach returns the desired output with a minimal amount of code.
>>>
Inputting a negative value will result in a
>>>
Inputting a decimal value results in a You can compare the execution times for each of the factorial methods using >>>
The sample above illustrates the results of
As you can see from the execution times, Not only is Find the Ceiling Value With ceil()
For example, an input of 5.43 will return the value 6, and an input of -12.43 will return the value -12.
When you input an integer value to >>>
>>>
When the value is positive (4.23), the function returns the next integer greater than the value (5). When the value is negative (-11.453), the function likewise returns the next integer greater than the value (-11). The function will return a >>>
You must input a number to
the function. If you try to input any other value, then you will get a Find the Floor Value With floor()
If you input an integer value, then the function will return the same value: >>>
As with >>>
When you input a positive decimal value (5.532), it will return the closest integer that is less than the input number (5). If you input a negative number (-6.432), then it will return the next lowest integer value (-7). If you try to input a value that is not a number, then the function will return a >>>
You can’t give non-number values as input to Truncate Numbers With trunc()When you get a number with a decimal point, you might want to keep only the integer part and eliminate the decimal part. The Dropping the decimal value is a type of rounding. With Here is how the >>>
As you can see, 12.32 is rounded downwards
towards 0, which gives the result 12. In the same way, -43.24 is rounded upwards towards 0, which gives the value -43. When dealing with positive numbers, >>>
When dealing with negative numbers, >>>
When the number is negative, Find the Closeness of Numbers With Python isclose()In certain situations—particularly in the data science field—you may need to determine whether two numbers are close to each other. But to do so, you first need to answer an important question: How close is close? In other words, what is the definition of close? Well, Merriam-Webster will tell you that close means “near in time, space, effect, or degree.” Not very helpful, is it? For example, take the following set of numbers: 2.32, 2.33, and 2.331. When you measure closeness by two decimal points, 2.32 and 2.33 are close. But in reality, 2.33 and 2.331 are closer. Closeness, therefore, is a relative concept. You can’t determine closeness without some kind of threshold. Fortunately, the Let’s check out how to compare two numbers using the default tolerances:
In the following case, 6 and 7 aren’t close: >>>
The numbers 6 and 7 aren’t considered close because the relative tolerance is set for nine decimal places. But if you input 6.999999999 and 7 under the same tolerance, then they are considered close: >>>
You can see that the value 6.999999999 is within nine decimal places of 7. Therefore, based on the default relative tolerance, 6.999999999 and 7 are considered close. You can adjust the relative tolerance however you want depending on your need. If you set >>>
You can observe that 6 and 7 are close now. This is because they are within 20% of each other. As with >>>
When you set the absolute tolerance to 1, the numbers 6 and 7 are close because the difference between them is equal to the absolute tolerance. However, in the second case, the difference between 6 and 7 is not less than or equal to the established absolute tolerance of 0.2. You can use the >>>
As you can see, you can determine the closeness of very small
numbers with >>>
You can see from the above examples that Power FunctionsThe power function takes any number x as input, raises x to some power n, and returns xn as output. Python’s Calculate the Power of a Number With pow()Power functions have the following formula where the variable x is the base, the variable n is the power, and a can be any constant: Power FunctionIn the formula above, the value of the base x is raised to the power of n. You can use
>>>
The first argument is the base value and the second argument is the power value. You can give an integer or a decimal value as input and the function always returns a float value. There are some special cases defined in When the base 1 is raised to the power of any number n, it gives the result 1.0: >>>
When you raise base value 1 to any power value, you will always get 1.0 as the result. Likewise, any base number raised to the power of 0 gives the result 1.0: >>>
As you can see, any number raised to the power of 0 will give 1.0 as the result. You can see that result even if the base is >>>
Zero raised to the power of any positive number will give 0.0 as the result: >>>
But if you try to raise 0.0 to a negative power, then the result will be a >>>
The Apart
from
The first option is straightforward. You may have used it a time or two already. The return type of the value is determined by the inputs: >>>
When you use integers, you get an integer value. When you use decimal values, the return type changes to a decimal value. The
second option is a versatile built-in function. You don’t have to use any imports to use it. The built-in
The first two parameters are mandatory, whereas the third parameter is optional. You can input integers or decimal numbers and the function will return the appropriate result based on the input: >>>
The built-in >>>
Even though all three methods of calculating power do the same thing, there are some implementation differences between them. The execution times for each method are as follows: >>>
The following table compares the execution times of the three methods as measured by
You can observe from the table that The reason behind the efficiency of Find the Natural Exponent With exp()You learned about power functions in the previous section. With exponential functions, things are a bit different. Instead of the base being the variable, power becomes the variable. It looks something like this: General Exponential FunctionHere a can be any constant, and x, which is the power value, becomes the variable. So what’s so special about exponential functions? The value of the function grows rapidly as the x value increases. If the base is greater than 1, then the function continuously increases in value as x increases. A special property of exponential functions is that the slope of the function also continuously increases as x increases. You learned about the Euler’s number in a previous section. It is the base of the natural logarithm. It also plays a role with the exponential function. When Euler’s number is incorporated into the exponential function, it becomes the natural exponential function: Natural Exponential FunctionThis function is used in many real-life situations. You may have heard of the term exponential growth, which is often used in relation to human population growth or rates of radioactive decay. Both of these can be calculated using the natural exponential function. The Python
>>>
The input number can be positive or negative, and the function always returns a float value. If the number is not a numerical value, then the method will return a >>>
As you can see, if the input is a string value, then the function returns a You can also calculate the exponent using the >>>
The following table compares the execution times of the above methods as measured by
You can see that It’s also worth noting that Practical Example With exp()Radioactive decay happens when an unstable atom loses energy by emitting ionizing radiation. The rate of radioactive decay is measured using half-life, which is the time it takes for half the amount of the parent nucleus to decay. You can calculate the decay process using the following formula: You can use the above formula to calculate the remaining quantity of a radioactive element after a certain number of years. The variables of the given formula are as follows:
Scientific research has identified the half-lives of all radioactive elements. You can substitute values to the equation to calculate the remaining quantity of any radioactive substance. Let’s try that now. The radioisotope strontium-90 has a half-life of 38.1 years. A sample contains 100 mg of Sr-90. You can calculate the remaining milligrams of Sr-90 after 100 years: >>>
As you can see, the half-life is set to 38.1 and the duration is set to 100 years. You can use Logarithmic FunctionsLogarithmic functions can be considered the inverse of exponential functions. They are denoted in the following form: General Logarithmic FunctionHere a is the base of the logarithm, which can be any number. You learned about exponential functions in a previous section. Exponential functions can be expressed in the form of logarithmic functions and vice versa. Python Natural Log With log()The natural logarithm of a number is its logarithm to the base of the mathematical constant e, or Euler’s number: Natural Logarithmic FunctionAs with the exponential function, natural log uses the constant e. It’s generally depicted as f(x) = ln(x), where e is implicit. You can use the natural log in the same way that you use the exponential function. It’s used to calculate values such as the rate of population growth or the rate of radioactive decay in elements.
>>>
However, the function returns a >>>
As you can see, you can’t input a negative value to With two arguments, you can calculate the log of the first argument to the base of the second argument: >>>
You can see how the value changes when the log base is changed. Understand log2() and log10()The Python
With >>>
Both functions have the same objective, but the Python documentation notes that You can calculate the log value of a number to base 10 with >>>
The
Python documentation also mentions that Practical Example With Natural LogIn a
previous section, you saw how to use By rearranging the radioactive decay formula, you can make the half-life (T) the subject of the formula. The variables of the given formula are as follows:
You can substitute the known values to the equation to calculate the half-life of a radioactive substance. For example, imagine you are studying an unidentified radioactive element sample. When it was discovered 100 years ago, the sample size was 100mg. After 100 years of decay, only 16.22mg is remaining. Using the formula above, you can calculate the half-life of this unknown element: >>>
You can see that the unknown element has a half-life of roughly 38.1 years. Based on this information, you can identify the unknown element as strontium-90. Other Important math Module FunctionsThe Python Calculate the Greatest Common DivisorThe greatest common divisor (GCD) of two positive numbers is the largest positive integer that divides both numbers without a remainder. For example, the GCD of 15 and 25 is 5. You can divide both 15 and 25 by 5 without any remainder. There is no greater number that does the same. If you take 15 and 30, then the GCD is 15 because both 15 and 30 can be divided by 15 without a remainder. You don’t have to implement your own functions to calculate GCD. The Python Calculate the Sum of IterablesIf you ever want to find the sum of the values of an iterable without using a loop, then Calculate the Square RootThe
square root of a number is a value that, when multiplied by itself, gives the number. You can use Convert Angle ValuesIn real-life scenarios as well as in mathematics, you often come across instances where you have to measure angles to perform calculations. Angles can be measured either by degrees or by radians. Sometimes you have to convert degrees to radians and vice versa. The If you want to convert degrees to radians,
then you can use Calculate Trigonometric ValuesTrigonometry is the study of triangles. It deals with the relationship between
angles and the sides of a triangle. Trigonometry is mostly interested in right-angled triangles (in which one internal angle is 90 degrees), but it can also be applied to other types of triangles. The Python You can calculate the sine value of an angle with New Additions to the math Module in Python 3.8With the release of Python version 3.8, a few new additions and changes have been made to the
cmath vs mathA complex number is a combination of a real number and an imaginary number. It has the formula of a + bi, where a is the real number and bi is the imaginary number. Real and imaginary numbers can be explained as follows:
A real number can be any number. For example, 12, 4.3, -19.0 are all real numbers. Imaginary numbers are shown as i. The following image shows an example of a complex number: Complex NumberIn the example above, 7 is the real number and 3i is the imaginary number. Complex numbers are mostly used in geometry, calculus, scientific calculations, and especially in electronics. The functions of the Python You can import the Since the >>>
As you can see, you can determine that a number is indeed complex by using Python also provides a special built-in function called >>>
You can use either method to create complex numbers. You can also use the >>>
This example shows you how to calculate the square root, logarithmic value, and exponential value of a complex number. You can read the documentation if you want to learn more about the NumPy vs mathSeveral notable Python libraries can be used for mathematical calculations. One of the most prominent libraries is Numerical Python, or NumPy. It is mainly used in scientific computing and in data science fields. Unlike the The heart of NumPy is the high-performance N-dimensional (multidimensional) array data structure. This array allows you to perform mathematical operations on an entire array without looping over the elements. All of the functions in the library are optimized to work with the N-dimensional array objects. Both the There are also several fundamental differences between When working with scalar values, ConclusionIn this article, you
learned about the Python In this article you’ve learned:
Understanding how to use the Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Exploring the Python math Module What is the use of math module in Python?Python provides the math module to deal with such calculations. Math module provides functions to deal with both basic operations such as addition(+), subtraction(-), multiplication(*), division(/) and advance operations like trigonometric, logarithmic, exponential functions.
Where is math module in Python?Python has a built-in math module. It is a standard module, so we don't need to install it separately. We only have to import it into the program we want to use. We can import the module, like any other module of Python, using import math to implement the functions to perform mathematical operations.
What is module in Python?A Python module is a file containing Python definitions and statements. A module can define functions, classes, and variables. A module can also include runnable code. Grouping related code into a module makes the code easier to understand and use. It also makes the code logically organized.
What is math called in Python?The Math Module
Python has also a built-in module called math , which extends the list of mathematical functions. When you have imported the math module, you can start using methods and constants of the module.
|