Which Of The Following Power Add Ins Is Best Suited For Editing Data Before Import
Sentry At present This tutorial has a related video class created by the Real Python team. Watch information technology together with the written tutorial to deepen your understanding: Exploring the Python math Module
In this commodity, you'll learn all almost Python'south math
module. Mathematical calculations are an essential function of near Python evolution. Whether yous're working on a scientific project, a financial application, or any other blazon of programming endeavour, you but tin can't escape the demand for math.
For straightforward mathematical calculations in Python, you tin use the born mathematical operators, such as add-on (+
), subtraction (-
), partition (/
), and multiplication (*
). But more advanced operations, such as exponential, logarithmic, trigonometric, or ability functions, are non congenital in. Does that mean you lot need to implement all of these functions from scratch?
Fortunately, no. Python provides a module specifically designed for higher-level mathematical operations: the math
module.
By the finish of this commodity, you lot'll acquire:
- What the Python
math
module is - How to use
math
module functions to solve real-life issues - What the constants of the
math
module are, including pi, tau, and Euler'southward number - What the differences between congenital-in functions and
math
functions are - What the differences between
math
,cmath
, and NumPy are
A background in mathematics will be helpful here, but don't worry if math isn't your strong adapt. This article will explain the basics of everything yous need to know.
And so let'due south get started!
Getting to Know the Python math
Module
The Python math
module is an important feature designed to deal with mathematical operations. It comes packaged with the standard Python release and has been there from the beginning. Most of the math
module's functions are thin wrappers around the C platform'south mathematical functions. Since its underlying functions are written in CPython, the math
module is efficient and conforms to the C standard.
The Python math
module offers yous the power to perform common and useful mathematical calculations within your application. Here are a few practical uses for the math
module:
- Calculating combinations and permutations using factorials
- Calculating the height of a pole using trigonometric functions
- Calculating radioactive decay using the exponential office
- Calculating the curve of a interruption bridge using hyperbolic functions
- Solving quadratic equations
- Simulating periodic functions, such as sound and light waves, using trigonometric functions
Since the math
module comes packaged with the Python release, you don't have to install it separately. Using it is just a matter of importing the module:
Y'all can import the Python math
module using the in a higher place command. After importing, you can use it straightaway.
Constants of the math
Module
The Python math
module offers a diverseness of predefined constants. Having access to these constants provides several advantages. For 1, you don't accept to manually hardcode them into your application, which saves you lot a lot of time. Plus, they provide consistency throughout your lawmaking. The module includes several famous mathematical constants and of import values:
- Pi
- Tau
- Euler's number
- Infinity
- Not a number (NaN)
In this department, you'll larn about the constants and how to use them in your Python lawmaking.
Pi
Pi (π) is the ratio of a circle's circumference (c) to its diameter (d):
π = c/d
This ratio is always the same for any circle.
Pi is an irrational number, which means information technology tin can't be expressed equally a uncomplicated fraction. Therefore, pi has an space number of decimal places, just information technology tin be approximated as 22/7, or three.141.
Yous can admission pi as follows:
>>>
>>> math . pi 3.141592653589793
As you lot tin run across, 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 past default, and math.pi
always returns a float value.
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:
>>>
>>> r = 3 >>> circumference = 2 * math . pi * r >>> f "Circumference of a Circle = 2 * { math . pi : .4 } * { r } = { circumference : .4 } " 'Circumference of a Circumvolve = two * 3.142 * 3 = xviii.85'
Yous can utilise math.pi
to summate the circumference of a circle. You can also calculate the expanse of a circumvolve using the formula πr² as follows:
>>>
>>> r = 5 >>> area = math . pi * r * r >>> f "Area of a Circle = { math . pi : .four } * { r } * { r } = { surface area : .4 } " 'Area of a Circumvolve = 3.142 * 5 * 5 = 78.54'
You can use math.pi
to summate the area and the circumference of a circle. When yous are doing mathematical calculations with Python and y'all come up across a formula that uses π, it's a best practice to utilize the pi value given by the math
module instead of hardcoding the value.
Tau
Tau (τ) 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 information technology'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 abiding, however, is still under debate. You have the freedom to use either 2π or τ as necessary.
You can utilize tau as below:
>>>
>>> math . tau vi.283185307179586
Similar math.pi
, math.tau
returns fifteen digits and is a float value. You can use tau to summate the circumference of a circle with τr, where r is the radius, as follows:
>>>
>>> r = three >>> circumference = math . tau * r >>> f "Circumference of a Circle = { math . tau : .iv } * { r } = { circumference : .4 } " 'Circumference of a Circumvolve = vi.283 * iii = xviii.85'
Yous tin can use math.tau
in place of 2 * math.pi
to tidy up equations that include the expression 2π.
Euler's Number
Euler'due south number (e) is a abiding that is the base of the natural logarithm, a mathematical function that is unremarkably used to calculate rates of growth or disuse. As with pi and tau, Euler'south number is an irrational number with space decimal places. The value of e is often approximated every bit 2.718.
Euler's number is an of import abiding considering information technology has many applied uses, such as computing population growth over time or determining rates of radioactive decay. Yous tin can admission Euler'southward number from the math
module as follows:
>>>
>>> math . e two.718281828459045
As with math.pi
and math.tau
, the value of math.eastward
is given to xv decimal places and is returned as a float value.
Infinity
Infinity can't be defined by a number. Rather, it's a mathematical concept representing something that is never-ending or boundless. Infinity tin 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:
>>>
>>> f "Positive Infinity = { math . inf } " 'Positive Infinity = inf' >>> f "Negative Infinity = { - math . inf } " 'Negative Infinity = -inf'
Infinity is non a numerical value. Instead, it's defined every bit math.inf
. Python introduced this constant in version iii.5 as an equivalent to float("inf")
:
>>>
>>> bladder ( "inf" ) == math . inf Truthful
Both float("inf")
and math.inf
represent the concept of infinity, making math.inf
greater than any numerical value:
>>>
>>> 10 = 1e308 >>> math . inf > x True
In the higher up lawmaking, math.inf
is greater than the value of x
, 10308 (the maximum size of a floating-point number), which is a double precision number.
Similarly, -math.inf
is smaller than whatever value:
>>>
>>> y = - 1e308 >>> y > - math . inf Truthful
Negative infinity is smaller than the value of y
, which is -10308. No number can exist greater than infinity or smaller than negative infinity. That's why mathematical operations with math.inf
don't change the value of infinity:
>>>
>>> math . inf + 1e308 inf >>> math . inf / 1e308 inf
As you tin can encounter, neither addition nor division changes the value of math.inf
.
Not a Number (NaN)
Not a number, or NaN, isn't actually a mathematical concept. It originated in the computer scientific discipline field as a reference to values that are not numeric. A NaN value can be due to invalid inputs, or information technology can betoken that a variable that should exist numerical has been corrupted by text characters or symbols.
It'south always a best practice to check if a value is NaN. If it is, so it could lead to invalid values in your program. Python introduced the NaN constant in version 3.5.
You can observe the value of math.nan
below:
NaN is not a numerical value. You can run into that the value of math.nan
is nan
, the same value as float("nan")
.
Arithmetic Functions
Number theory is a co-operative of pure mathematics, which is the study of natural numbers. Number theory usually deals with positive whole numbers or integers.
The Python math
module provides functions that are useful in number theory as well as in representation theory, a related field. These functions allow y'all to calculate a range of important values, including the following:
- The factorials of a number
- The greatest common divisor of ii numbers
- The sum of iterables
Find Factorials With Python factorial()
You may have seen mathematical expressions like 7! or 4! before. The assertion 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 downwardly to 1.
The following table shows the factorial values for four, 6, and 7:
Symbol | In Words | Expression | Result |
---|---|---|---|
iv! | 4 factorial | 4 ten 3 x 2 x 1 | 24 |
6! | Vi factorial | 6 x 5 x four x 3 ten 2 x ane | 720 |
7! | Vii factorial | 7 x half-dozen ten 5 ten 4 x three x 2 x ane | 5040 |
Yous tin can encounter from the table that 4!, or four factorial, gives the value 24 by multiplying the range of whole numbers from 4 to 1. Similarly, half dozen! and 7! give the values 720 and 5040, respectively.
You lot can implement a factorial function in Python using 1 of several tools:
-
for
loops - Recursive functions
-
math.factorial()
First you are going to await at a factorial implementation using a for
loop. This is a relatively straightforward approach:
def fact_loop ( num ): if num < 0 : return 0 if num == 0 : return 1 factorial = one for i in range ( 1 , num + 1 ): factorial = factorial * i return factorial
You can as well use a recursive part to find the factorial. This is more complicated but likewise more elegant than using a for
loop. You can implement the recursive office as follows:
def fact_recursion ( num ): if num < 0 : return 0 if num == 0 : return 1 return num * fact_recursion ( num - 1 )
The post-obit example illustrates how you can utilise the for
loop and recursive functions:
>>>
>>> fact_loop ( seven ) 5040 >>> fact_recursion ( 7 ) 5040
Even though their implementations are different, their return values are the aforementioned.
Yet, implementing functions of your own just to become the factorial of a number is time consuming and inefficient. A better method is to use math.factorial()
. Here'south how y'all tin detect the factorial of a number using math.factorial()
:
>>>
>>> math . factorial ( vii ) 5040
This approach returns the desired output with a minimal amount of code.
factorial()
accepts only positive integer values. If you effort to input a negative value, so you will get a ValueError
:
>>>
>>> math . factorial ( - v ) Traceback (well-nigh recent telephone call last): File "<stdin>", line one, in <module> ValueError: factorial() non defined for negative values
Inputting a negative value volition result in a ValueError
reading factorial() not defined for negative values
.
factorial()
doesn't have decimal numbers, either. It will give you a ValueError
:
>>>
>>> math . factorial ( 4.3 ) Traceback (most recent call terminal): File "<stdin>", line ane, in <module> ValueError: factorial() only accepts integral values
Inputting a decimal value results in a ValueError
reading factorial() only accepts integral values
.
You tin compare the execution times for each of the factorial methods using timeit()
:
>>>
>>> import timeit >>> timeit . timeit ( "fact_loop(10)" , globals = globals ()) 1.063997201999996 >>> timeit . timeit ( "fact_recursion(ten)" , globals = globals ()) 1.815312818999928 >>> timeit . timeit ( "math.factorial(ten)" , setup = "import math" ) 0.10671788000001925
The sample above illustrates the results of timeit()
for each of the three factorial methods.
timeit()
executes one million loops each time it is run. The post-obit table compares the execution times of the 3 factorial methods:
Blazon | Execution Time |
---|---|
With loops | 1.0640 s |
With recursion | 1.8153 s |
With factorial() | 0.1067 s |
Equally y'all can run into from the execution times, factorial()
is faster than the other methods. That's because of its underlying C implementation. The recursion-based method is the slowest out of the three. Although you might go different timings depending on your CPU, the order of the functions should exist the same.
Not simply is factorial()
faster than the other methods, but information technology'due south besides more than stable. When you implement your own function, you take to explicitly code for disaster cases such as treatment negative or decimal numbers. One mistake in the implementation could lead to bugs. But when using factorial()
, you don't have to worry virtually disaster cases considering the role handles them all. Therefore, it's a best exercise to utilize factorial()
whenever possible.
Find the Ceiling Value With ceil()
math.ceil()
will render the smallest integer value that is greater than or equal to the given number. If the number is a positive or negative decimal, and then the function will return the next integer value greater than the given value.
For example, an input of v.43 will return the value 6, and an input of -12.43 will render the value -12. math.ceil()
tin accept positive or negative real numbers every bit input values and will always return an integer value.
When you input an integer value to ceil()
, it will return the same number:
>>>
>>> math . ceil ( 6 ) six >>> math . ceil ( - 11 ) -11
math.ceil()
always returns the same value when an integer is given as input. To encounter the truthful nature of ceil()
, yous have to input decimal values:
>>>
>>> math . ceil ( 4.23 ) 5 >>> math . ceil ( - 11.453 ) -11
When the value is positive (4.23), the role returns the next integer greater than the value (five). When the value is negative (-11.453), the function too returns the next integer greater than the value (-xi).
The office will return a TypeError
if you input a value that is not a number:
>>>
>>> math . ceil ( "x" ) Traceback (nearly recent call last): File "<stdin>", line 1, in <module> TypeError: must be real number, non str
You must input a number to the office. If you endeavor to input whatever other value, so you will become a TypeError
.
Find the Floor Value With floor()
floor()
will return the closest integer value that is less than or equal to the given number. This office behaves opposite to ceil()
. For example, an input of viii.72 volition return viii, and an input of -12.34 will return -thirteen. flooring()
can accept either positive or negative numbers as input and will return an integer value.
If you input an integer value, then the function volition return the same value:
>>>
>>> math . floor ( four ) 4 >>> math . floor ( - 17 ) -17
As with ceil()
, when the input for floor()
is an integer, the issue will be the same as the input number. The output just differs from the input when you input decimal values:
>>>
>>> math . floor ( 5.532 ) 5 >>> math . flooring ( - vi.432 ) -vii
When y'all input a positive decimal value (v.532), it will return the closest integer that is less than the input number (5). If you lot input a negative number (-6.432), and then it will return the next lowest integer value (-7).
If yous try to input a value that is non a number, then the part will return a TypeError
:
>>>
>>> math . flooring ( "x" ) Traceback (most recent call last): File "<stdin>", line one, in <module> TypeError: must be real number, not str
Yous can't requite non-number values as input to ceil()
. Doing so will result in a TypeError
.
Truncate Numbers With trunc()
When you get a number with a decimal betoken, you might want to keep only the integer function and eliminate the decimal function. The math
module has a function called trunc()
which lets you do just that.
Dropping the decimal value is a blazon of rounding. With trunc()
, negative numbers are always rounded upwards toward zero and positive numbers are always rounded downwards toward zero.
Here is how the trunc()
part rounds off positive or negative numbers:
>>>
>>> math . trunc ( 12.32 ) 12 >>> math . trunc ( - 43.24 ) -43
Every bit y'all can see, 12.32 is rounded downward towards 0, which gives the result 12. In the same way, -43.24 is rounded upwards towards 0, which gives the value -43. trunc()
always rounds towards cypher regardless of whether the number is positive or negative.
When dealing with positive numbers, trunc()
behaves the aforementioned every bit floor()
:
>>>
>>> math . trunc ( 12.32 ) == math . floor ( 12.32 ) Truthful
trunc()
behaves the same equally flooring()
for positive numbers. Equally you lot can see, the render value of both functions is the aforementioned.
When dealing with negative numbers, trunc()
behaves the same as ceil()
:
>>>
>>> math . trunc ( - 43.24 ) == math . ceil ( - 43.24 ) True
When the number is negative, floor()
behaves the same as ceil()
. The return values of both functions are the same.
Find the Closeness of Numbers With Python isclose()
In certain situations—particularly in the data science field—yous may demand to determine whether two numbers are close to each other. But to do so, you get-go need to answer an important question: How shut is close? In other words, what is the definition of close?
Well, Merriam-Webster will tell yous that close means "near in time, space, effect, or degree." Not very helpful, is it?
For example, accept the following fix of numbers: two.32, 2.33, and ii.331. When you measure closeness past two decimal points, 2.32 and 2.33 are close. Just in reality, 2.33 and 2.331 are closer. Closeness, therefore, is a relative concept. Yous can't determine closeness without some kind of threshold.
Fortunately, the math
module provides a function chosen isclose()
that lets you set your ain threshold, or tolerance, for closeness. It returns True
if two numbers are within your established tolerance for closeness and otherwise returns Fake
.
Allow's check out how to compare two numbers using the default tolerances:
- Relative tolerance, or rel_tol, is the maximum divergence for being considered "close" relative to the magnitude of the input values. This is the pct of tolerance. The default value is 1e-09 or 0.000000001.
- Accented tolerance, or abs_tol, is the maximum departure for being considered "close" regardless of the magnitude of the input values. The default value is 0.0.
isclose()
will render Truthful
when the post-obit status is satisfied:
abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol).
isclose
uses the above expression to determine the closeness of two numbers. You can substitute your own values and observe whether whatever two numbers are close.
In the post-obit case, half-dozen and vii aren't close:
>>>
>>> math . isclose ( half-dozen , 7 ) False
The numbers 6 and 7 aren't considered shut considering the relative tolerance is gear up for nine decimal places. Only if you input 6.999999999 and 7 under the same tolerance, then they are considered shut:
>>>
>>> math . isclose ( half dozen.999999999 , 7 ) True
You can come across 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 shut.
You can adjust the relative tolerance however you want depending on your demand. If you set rel_tol
to 0.2, then 6 and 7 are considered close:
>>>
>>> math . isclose ( six , 7 , rel_tol = 0.2 ) True
Y'all can find that 6 and vii are close now. This is because they are within 20% of each other.
As with rel_tol
, you lot tin adjust the abs_tol
value according to your needs. To exist considered close, the departure between the input values must be less than or equal to the absolute tolerance value. Yous tin can set the abs_tol
as follows:
>>>
>>> math . isclose ( vi , vii , abs_tol = ane.0 ) Truthful >>> math . isclose ( 6 , seven , abs_tol = 0.2 ) Fake
When you ready the accented tolerance to 1, the numbers 6 and 7 are shut considering the departure betwixt them is equal to the accented 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.two.
You tin use the abs_tol
for very small values:
>>>
>>> math . isclose ( 1 , i.0000001 , abs_tol = 1e-08 ) Fake >>> math . isclose ( one , i.00000001 , abs_tol = 1e-08 ) True
As yous tin see, you tin can determine the closeness of very small numbers with isclose
. A few special cases regarding closeness tin can exist illustrated using nan
and inf
values:
>>>
>>> math . isclose ( math . nan , 1e308 ) False >>> math . isclose ( math . nan , math . nan ) False >>> math . isclose ( math . inf , 1e308 ) False >>> math . isclose ( math . inf , math . inf ) True
You can see from the above examples that nan
is not close to any value, non even to itself. On the other paw, inf
is not close to whatever numerical values, not even to very large ones, but it is shut to itself.
Power Functions
The power part takes any number 10 equally input, raises 10 to some power due north, and returns tennorthward every bit output. Python'south math
module provides several power-related functions. In this section, y'all'll learn virtually power functions, exponential functions, and square root functions.
Calculate the Ability of a Number With pow()
Power functions have the following formula where the variable x is the base, the variable due north is the power, and a can be any abiding:
In the formula above, the value of the base x is raised to the power of n.
You can apply math.pow()
to go the power of a number. There is a congenital-in function, prisoner of war()
, that is different from math.pw()
. You volition learn the divergence after in this department.
math.pow()
takes two parameters every bit follows:
>>>
>>> math . pow ( 2 , 5 ) 32.0 >>> math . pow ( 5 , ii.4 ) 47.59134846789696
The get-go argument is the base of operations value and the second argument is the power value. You can give an integer or a decimal value equally input and the function always returns a float value. There are some special cases divers in math.prisoner of war()
.
When the base 1 is raised to the power of any number n, it gives the consequence 1.0:
>>>
>>> math . prisoner of war ( 1.0 , iii ) 1.0
When you raise base value ane to whatsoever power value, you will always get 1.0 every bit the event. Likewise, whatever base number raised to the power of 0 gives the result 1.0:
>>>
>>> math . pw ( 4 , 0.0 ) i.0 >>> math . pw ( - 4 , 0.0 ) i.0
As you lot tin can see, whatever number raised to the power of 0 will give 1.0 as the result. You tin can see that event even if the base of operations is nan
:
>>>
>>> math . pow ( math . nan , 0.0 ) 1.0
Naught raised to the ability of any positive number will give 0.0 every bit the result:
>>>
>>> math . pow ( 0.0 , 2 ) 0.0 >>> math . pow ( 0.0 , 2.iii ) 0.0
Only if you lot try to raise 0.0 to a negative power, and so the result will be a ValueError
:
>>>
>>> math . pow ( 0.0 , - 2 ) Traceback (most contempo phone call last): File "<stdin>", line i, in <module> ValueError: math domain error
The ValueError
just occurs when the base is 0. If the base is whatever other number except 0, and then the function will return a valid ability value.
Autonomously from math.pw()
, in that location are two congenital-in means of finding the power of a number in Python:
-
10 ** y
-
pow()
The outset option is straightforward. You may have used it a time or ii already. The render type of the value is determined by the inputs:
>>>
>>> iii ** ii 9 >>> two ** 3.3 9.849155306759329
When y'all use integers, you become an integer value. When yous utilize decimal values, the render blazon changes to a decimal value.
The second option is a versatile built-in function. Yous don't have to use whatever imports to apply information technology. The built-in pw()
method has three parameters:
- The base number
- The power number
- The modulus number
The start 2 parameters are mandatory, whereas the third parameter is optional. You can input integers or decimal numbers and the function volition return the advisable result based on the input:
>>>
>>> prisoner of war ( 3 , two ) 9 >>> pow ( 2 , 3.3 ) nine.849155306759329
The built-in prisoner of war()
has ii required arguments that work the same as the base and power in the 10 ** y
syntax. pow()
likewise has a tertiary parameter that is optional: modulus. This parameter is often used in cryptography. Built-in pow()
with the optional modulus parameter is equivalent to the equation (x ** y) % z
. The Python syntax looks similar this:
>>>
>>> pw ( 32 , six , 5 ) 4 >>> ( 32 ** 6 ) % v == pow ( 32 , 6 , 5 ) True
pow()
raises the base (32) to the power (6), and then the result value is modulo divided past the modulus number (5). In this instance, the result is iv. You tin can substitute your own values and see that both pow()
and the given equation provide the same results.
Even though all iii methods of calculating power do the same thing, there are some implementation differences between them. The execution times for each method are as follows:
>>>
>>> timeit . timeit ( "10 ** 308" ) 1.0078728999942541 >>> timeit . timeit ( "pow(10, 308)" ) 1.047615700008464 >>> timeit . timeit ( "math.pow(10, 308)" , setup = "import math" ) 0.1837239999877056
The following table compares the execution times of the iii methods as measured by timeit()
:
Blazon | Execution Time |
---|---|
x ** y | 1.0079 s |
prisoner of war(x, y) | 1.0476 s |
math.pow(ten, y) | 0.1837 s |
You can observe from the table that math.pow()
is faster than the other methods and built-in prisoner of war()
is the slowest.
The reason behind the efficiency of math.pow()
is the style that it'due south implemented. It relies on the underlying C linguistic communication. On the other hand, pow()
and x ** y
apply the input object'southward own implementation of the **
operator. However, math.pow()
can't handle complex numbers (which volition exist explained in a afterward section), whereas pow()
and **
can.
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 of operations being the variable, ability becomes the variable. It looks something like this:
Here a tin be whatsoever constant, and 10, which is the power value, becomes the variable.
And then what's so special most exponential functions? The value of the function grows quickly as the x value increases. If the base is greater than i, and then the function continuously increases in value as x increases. A special property of exponential functions is that the slope of the function likewise continuously increases every bit 10 increases.
You learned about the Euler'due south number in a previous section. It is the base of operations of the natural logarithm. It also plays a role with the exponential role. When Euler'due south number is incorporated into the exponential function, information technology becomes the natural exponential function:
This function is used in many existent-life situations. Yous may have heard of the term exponential growth, which is often used in relation to homo population growth or rates of radioactive decay. Both of these can exist calculated using the natural exponential part.
The Python math
module provides a function, exp()
, that lets you lot summate the natural exponent of a number. Yous tin can discover the value equally follows:
>>>
>>> math . exp ( 21 ) 1318815734.4832146 >>> math . exp ( - i.ii ) 0.30119421191220214
The input number tin be positive or negative, and the function always returns a bladder value. If the number is not a numerical value, then the method volition return a TypeError
:
>>>
>>> math . exp ( "ten" ) Traceback (virtually recent call final): File "<stdin>", line 1, in <module> TypeError: must be real number, not str
Every bit you can see, if the input is a cord value, then the part returns a TypeError
reading must exist real number, not str
.
You tin also calculate the exponent using the math.e ** x
expression or past using pow(math.eastward, x)
. The execution times of these three methods are equally follows:
>>>
>>> timeit . timeit ( "math.eastward ** 308" , setup = "import math" ) 0.17853009998701513 >>> timeit . timeit ( "prisoner of war(math.e, 308)" , setup = "import math" ) 0.21040189999621361 >>> timeit . timeit ( "math.exp(308)" , setup = "import math" ) 0.125878200007719
The following table compares the execution times of the in a higher place methods every bit measured by timeit()
:
Type | Execution Time |
---|---|
east ** x | 0.1785 south |
pow(e, ten) | 0.2104 southward |
math.exp(x) | 0.1259 s |
You can see that math.exp()
is faster than the other methods and prisoner of war(e, x)
is the slowest. This is the expected behavior because of the underlying C implementation of the math
module.
It'southward as well worth noting that due east ** ten
and pow(east, x)
render the aforementioned values, simply exp()
returns a slightly unlike value. This is due to implementation differences. Python documentation notes that exp()
is more accurate than the other two methods.
Practical Example With exp()
Radioactive decay happens when an unstable atom loses energy by emitting ionizing radiation. The rate of radioactive disuse is measured using half-life, which is the time it takes for half the amount of the parent nucleus to disuse. You can calculate the decay procedure using the post-obit formula:
You lot can use the above formula to calculate the remaining quantity of a radioactive element afterwards a certain number of years. The variables of the given formula are as follows:
- N(0) is the initial quantity of the substance.
- N(t) is the quantity that even so remains and has not nonetheless decayed after a time (t).
- T is the one-half-life of the decomposable quantity.
- east is Euler'south number.
Scientific inquiry has identified the half-lives of all radioactive elements. You can substitute values to the equation to calculate the remaining quantity of whatsoever radioactive substance. Let'southward endeavor that now.
The radioisotope strontium-90 has a half-life of 38.1 years. A sample contains 100 mg of Sr-ninety. You can calculate the remaining milligrams of Sr-ninety afterwards 100 years:
>>>
>>> half_life = 38.1 >>> initial = 100 >>> time = 100 >>> remaining = initial * math . exp ( - 0.693 * time / half_life ) >>> f "Remaining quantity of Sr-90: { remaining } " 'Remaining quantity of Sr-90: sixteen.22044604811303'
Equally yous tin can meet, the one-half-life is set to 38.i and the duration is set up to 100 years. Y'all can utilize math.exp
to simplify the equation. Past substituting the values to the equation you can discover that, afterwards 100 years, 16.22mg of Sr-90 remains.
Logarithmic Functions
Logarithmic functions can be considered the inverse of exponential functions. They are denoted in the post-obit class:
Here a is the base of the logarithm, which tin can exist any number. You lot learned about exponential functions in a previous department. Exponential functions tin 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 operations of the mathematical constant east, or Euler'southward number:
Equally with the exponential function, natural log uses the constant due east. Information technology'due south generally depicted as f(x) = ln(x), where e is implicit.
You tin apply the natural log in the same mode that you use the exponential function. Information technology's used to calculate values such as the charge per unit of population growth or the rate of radioactivity in elements.
log()
has two arguments. The first i is mandatory and the second one is optional. With 1 argument you lot can get the natural log (to the base eastward) of the input number:
>>>
>>> math . log ( 4 ) 1.3862943611198906 >>> math . log ( 3.4 ) ane.2237754316221157
Even so, the function returns a ValueError
if you input a not-positive number:
>>>
>>> math . log ( - 3 ) Traceback (most recent call last): File "<stdin>", line ane, in <module> ValueError: math domain error
Every bit you lot can see, you can't input a negative value to log()
. This is because log values are undefined for negative numbers and zero.
With two arguments, you lot can calculate the log of the first argument to the base of operations of the second statement:
>>>
>>> math . log ( math . pi , 2 ) one.651496129472319 >>> math . log ( math . pi , 5 ) 0.711260668712669
Y'all tin encounter how the value changes when the log base of operations is changed.
Understand log2()
and log10()
The Python math
module also provides two separate functions that let you calculate the log values to the base of two and 10:
-
log2()
is used to summate the log value to the base two. -
log10()
is used to calculate the log value to the base x.
With log2()
y'all can go the log value to the base ii:
>>>
>>> math . log2 ( math . pi ) 1.6514961294723187 >>> math . log ( math . pi , two ) 1.651496129472319
Both functions have the same objective, but the Python documentation notes that log2()
is more accurate than using log(x, 2)
.
You lot can calculate the log value of a number to base x with log10()
:
>>>
>>> math . log10 ( math . pi ) 0.4971498726941338 >>> math . log ( math . pi , x ) 0.4971498726941338
The Python documentation also mentions that log10()
is more accurate than log(x, 10)
fifty-fifty though both functions have the aforementioned objective.
Applied Instance With Natural Log
In a previous section, you saw how to utilize math.exp()
to calculate the remaining corporeality of a radioactive element later on a certain menses of time. With math.log()
, y'all can find the half-life of an unknown radioactive element by measuring the mass at an interval. The following equation can be used to calculate the half-life of a radioactive chemical element:
By rearranging the radioactive decay formula, you lot can make the half-life (T) the subject of the formula. The variables of the given formula are as follows:
- T is the half-life of the decaying quantity.
- N(0) is the initial quantity of the substance.
- N(t) is the quantity that remains and has not all the same decayed afterwards a menstruation of time (t).
- ln is the natural log.
You tin substitute the known values to the equation to calculate the half-life of a radioactive substance.
For example, imagine y'all are studying an unidentified radioactive chemical element sample. When it was discovered 100 years ago, the sample size was 100mg. After 100 years of decay, simply 16.22mg is remaining. Using the formula above, you can calculate the half-life of this unknown element:
>>>
>>> initial = 100 >>> remaining = sixteen.22 >>> time = 100 >>> half_life = ( - 0.693 * time ) / math . log ( remaining / initial ) >>> f "Half-life of the unknown element: { half_life } " 'One-half-life of the unknown element: 38.09942398335152'
You lot can see that the unknown element has a half-life of roughly 38.1 years. Based on this data, you can identify the unknown chemical element every bit strontium-90.
Other Of import math
Module Functions
The Python math
module has many useful functions for mathematical calculations, and this commodity only covered a few of them in depth. In this section, you will briefly learn about some of the other important functions available in the math
module.
Calculate the Greatest Common Divisor
The greatest mutual divisor (GCD) of two positive numbers is the largest positive integer that divides both numbers without a remainder.
For instance, the GCD of xv and 25 is 5. Yous can divide both 15 and 25 by five without any remainder. In that location is no greater number that does the aforementioned. If you take 15 and xxx, then the GCD is xv because both xv and thirty can be divided by 15 without a remainder.
Y'all don't have to implement your own functions to summate GCD. The Python math
module provides a function called math.gcd()
that allows you lot to calculate the GCD of two numbers. You can give positive or negative numbers as input, and it returns the appropriate GCD value. You tin't input a decimal number, even so.
Calculate the Sum of Iterables
If y'all ever desire to find the sum of the values of an iterable without using a loop, then math.fsum()
is probably the easiest fashion to do so. You can use iterables such as arrays, tuples, or lists as input and the function returns the sum of the values. A built-in part called sum()
lets yous calculate the sum of iterables as well, merely fsum()
is more accurate than sum()
. You can read more nigh that in the documentation.
Calculate the Square Root
The foursquare root of a number is a value that, when multiplied by itself, gives the number. Yous can use math.sqrt()
to notice the square root of whatsoever positive existent number (integer or decimal). The return value is always a float value. The office volition throw a ValueError
if you try to enter a negative number.
Catechumen Angle Values
In real-life scenarios equally well equally in mathematics, y'all often come beyond instances where you accept to mensurate angles to perform calculations. Angles tin be measured either past degrees or by radians. Sometimes yous have to catechumen degrees to radians and vice versa. The math
module provides functions that let you do so.
If you want to convert degrees to radians, then you can employ math.radians()
. Information technology returns the radian value of the degree input. Also, if y'all want to convert radians to degrees, and then you can use math.degrees()
.
Calculate Trigonometric Values
Trigonometry is the study of triangles. It deals with the relationship between angles and the sides of a triangle. Trigonometry is more often than not interested in right-angled triangles (in which ane internal angle is 90 degrees), but it can also be practical to other types of triangles. The Python math
module provides very useful functions that allow yous perform trigonometric calculations.
You tin calculate the sine value of an angle with math.sin()
, the cosine value with math.cos()
, and the tangent value with math.tan()
. The math
module also provides functions to calculate arc sine with math.asin()
, arc cosine with math.acos()
, and arc tangent with math.atan()
. Finally, you can summate the hypotenuse of a triangle using math.hypot()
.
New Additions to the math
Module in Python 3.eight
With the release of Python version 3.8, a few new additions and changes take been made to the math
module. The new additions and changes are equally follows:
-
comb(due north, k)
returns the number of ways to cull g items from n items without repetition and without particular lodge. -
perm(n, k)
returns the number of ways to choose k items from northward items without repetition and with guild. -
isqrt()
returns the integer foursquare root of a non-negative integer. -
prod()
calculates the product of all of the elements in the input iterable. As withfsum()
, this method tin can take iterables such as arrays, lists, or tuples. -
dist()
returns the Euclidean altitude betwixt two points p and q, each given every bit a sequence (or iterable) of coordinates. The 2 points must accept the same dimension. -
hypot()
now handles more than two dimensions. Previously, it supported a maximum of two dimensions.
cmath
vs math
A 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 tin can be explained every bit follows:
- A real number is literally any number you can think of.
- An imaginary number is a number that gives a negative result when squared.
A existent number tin can be whatever 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 circuitous number:
In the example to a higher place, 7 is the existent 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 math
module aren't equipped to handle complex numbers. However, Python provides a different module that can specifically deal with complex numbers, the cmath
module. The Python math
module is complemented past the cmath
module, which implements many of the same functions just for circuitous numbers.
Y'all can import the cmath
module equally follows:
Since the cmath
module is too packaged with Python, you tin can import it the same way you imported the math
module. Before y'all work with the cmath
module, yous take to know how to ascertain a complex number. You lot tin can define a complex number every bit follows:
>>>
>>> c = 2 + iii j >>> c (2+3j) >>> type ( c ) <class 'complex'>
As you tin can encounter, you can determine that a number is indeed complex by using blazon()
.
Python besides provides a special congenital-in office called complex()
that lets you create complex numbers. You can use complex()
as follows:
>>>
>>> c = complex ( ii , 3 ) >>> c (2+3j) >>> type ( c ) <class 'circuitous'>
You can use either method to create complex numbers. You can likewise employ the cmath
module to summate mathematical functions for complex numbers as follows:
>>>
>>> cmath . sqrt ( c ) (i.8581072140693775+0.6727275964137814j) >>> cmath . log ( c ) (i.3622897515267103+0.6947382761967031j) >>> cmath . exp ( c ) (-sixteen.091399670844+12.02063434789931j)
This case shows yous how to summate the foursquare root, logarithmic value, and exponential value of a complex number. You can read the documentation if y'all want to acquire more about the cmath
module.
NumPy vs math
Several notable Python libraries tin can be used for mathematical calculations. One of the nigh prominent libraries is Numerical Python, or NumPy. It is mainly used in scientific computing and in data scientific discipline fields. Unlike the math
module, which is part of the standard Python release, you take to install NumPy in order to work with it.
The heart of NumPy is the high-functioning Northward-dimensional (multidimensional) array information construction. 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 North-dimensional assortment objects.
Both the math
module and the NumPy library can be used for mathematical calculations. NumPy has several similarities with the math
module. NumPy has a subset of functions, similar to math
module functions, that bargain with mathematical calculations. Both NumPy and math
provide functions that bargain with trigonometric, exponential, logarithmic, hyperbolic and arithmetic calculations.
There are as well several central differences between math
and NumPy. The Python math
module is geared more towards working with scalar values, whereas NumPy is better suited for working with arrays, vectors, and fifty-fifty matrices.
When working with scalar values, math
module functions can exist faster than their NumPy counterparts. This is because the NumPy functions convert the values to arrays under the hood in club to perform calculations on them. NumPy is much faster when working with Northward-dimensional arrays because of the optimizations for them. Except for fsum()
and prod()
, the math
module functions can't handle arrays.
Conclusion
In this article, you learned about the Python math
module. The module provides useful functions for performing mathematical calculations that have many applied applications.
In this article y'all've learned:
- What the Python
math
module is - How to employ
math
functions with applied examples - What the constants of the
math
module, including pi, tau, and Euler's number are - What the differences between built-in functions and
math
functions are - What the differences between
math
,cmath
, and NumPy are
Understanding how to utilise the math
functions is the first step. Now it's fourth dimension to start applying what you learned to existent-life situations. If you have any questions or comments, then please exit them in the comments section beneath.
Sentry At present This tutorial has a related video course created by the Real Python team. Watch information technology together with the written tutorial to deepen your understanding: Exploring the Python math Module
Which Of The Following Power Add Ins Is Best Suited For Editing Data Before Import,
Source: https://realpython.com/python-math-module/
Posted by: vogelsaind1971.blogspot.com
0 Response to "Which Of The Following Power Add Ins Is Best Suited For Editing Data Before Import"
Post a Comment