Using math in python

Using The math Module in Python

math is a built-in module in the Python 3 standard library that provides standard mathematical constants and functions. You can use the math module to perform various mathematical calculations, such as numeric, trigonometric, logarithmic, and exponential calculations.

This tutorial will explore the common constants and functions implemented in the math module — and how to use them.

The math Module Constants

There are several built-in constants in the math module. We’ll cover some of the most important constants in this section.

math.pi

The number 𝜋 is a mathematical constant, approximately equal to 3.14159. After importing the math module, you just need to write math.pi to access the 𝜋 number:

Let’s use the 𝜋 number to calculate the area of a circle. The formula for calculating a circle area is as follows:

import math def circle_area(r): return math.pi*r**2 radius = 3 print("Area language-python">print(math.tau)

math.e

We can access the number e (or the Euler’s number) simply by using the math.e constant:

math.nan

The math.nan constant stands for Not a Number, and it can initialize those variables that aren’t numbers. Technically, the data type of the math.nan constant is float; however, it’s not considered a valid number.

print(math.nan) print(type(math.nan))

math.inf

The math.inf constant represents a floating-point positive infinity. It can represent both positive infinity and negative infinity constants, as follows:

print(math.inf) print(-math.inf)

The math Module Functions

The math module provides a wide range of mathematical functions for many different scientific and engineering applications, including the following:

  • Number functions
  • Power and logarithmic functions
  • Trigonometric functions
  • Angular conversion functions
  • Hyperbolic functions
  • and some special functions

However, we will only discuss the most important ones in this section. Let’s explore them.

Number Functions

math.ceil()

The math.ceil() method maps a floating-point number to the smallest succeeding integer:

math.floor()

The math.floor() method maps a floating-point number to the greatest preceeding integer:

math.factorial()

The math.factorial(n) method returns the product of all natural numbers less than or equal to n , if n a positive integer. However, if n = 0 , it returns 1 . The code below uses the math.factorial() to calculate $5!$:

n = 5 print("<>! = <>".format(n, math.factorial(n)))

math.gcd()

The math.gcd() method returns the greatest common denominator for two numbers; we can use it to reduce fractions.

For example, the GCD for 25 and 120 is 5, so we can divide the numerator and denominator by 5 to get a reduced fraction (e.g., $\frac = \frac$). Let’s see how it works:

gcd = math.gcd(25, 120) print(gcd)

math.fabs()

The math.fabs() method removes the negative sign of a given number, if any, and returns its absolute value as a float:

Читайте также:  Php json значение по ключу

Power and Logarithmic Functions

math.pow()

The math.pow() method returns a floating-point value representing the value of x to the power of y $(x^y)$. Let’s try the math.pow() method by forecasting an investment. To do that, we need to know the initial deposit, the annual interest rate, and the number of years that you invest your money in an investment account. Finally, by using the following formula, we can calculate the final amount of the investment:

For example, consider the following values:

The code calculates the final amount deposited in the investment account after five years:

deposit = 10000 interest_rate = 0.04 number_years = 5 final_amount = deposit * math.pow(1 + interest_rate, number_years) print("The final amount after five years is", final_amount)
The final amount after five years is 12166.529024000001

The math.pow(x, y) method always returns a floating-point value, Let’s check the data type of the function’s return value:

math.exp()

The math.exp(x) method is equal to $e^x$, where $e$ is the Euler’s number. We can say the math.exp(x) method is equivalent to the statement below:

print(math.exp(3)) print(math.pow(math.e, 3))
20.085536923187668 20.085536923187664

math.sqrt()

The math.sqrt() method returns the square root of a number. Let’s try it:

math.log()

The math.log() method accepts two arguments, x and base , where the default value of base is $e$. So the method returns the natural logarithm of x $(\log_e x)$ if we only pass one argument. On the other hand, if we provide two arguments, it calculates the logarithm of x to the given base ($\log_b x$). Let’s calculate different logarithms:

print(math.log(10)) print(math.log(10, 3))
2.302585092994046 2.095903274289385

The first line returns the natural logarithm of 10, and the second line returns the logarithm of 10 to the base 3.

Although we’re able to calculate the logarithm of any number to the base 10 using math.log(x, 10) , the math module provides a more accurate method to perform the same calculation. Let’s check it out:

Trigonometric Functions

The math module also provides some useful methods for doing trigonometry. In this section, we’ll learn how to calculate the sine, cosine, and tangent of a given value using the following methods provided in the math module.

math.sin()

The math.sin() method returns the sine of a given value, where the value must be in radians. The returned value is a floating-point number between -1 and 1:

math.cos()

The math.cos() method returns the cosine of a given value, and like the math.sin() method, the value must be in radians. The returned value is a floating-point number between -1 and 1:

math.tan()

The math.tan() method returns a floating-point value representing the tangent of a given value. The value must be in radians. Let’s find the tangent of different angles:

print(math.tan(math.pi/4)) print(math.tan(math.pi/6)) print(math.tan(0))
0.9999999999999999 0.5773502691896257 0.0

The math‍‍‍ module provides two useful methods for angular conversion. To convert a given angle from radians to degrees, use the math.degrees() , and to convert a given angle from degrees to radians, use math.radians(x) .

Hyperbolic Functions

The hyperbolic functions are quite similar to the trigonometric functions; however, there are differences. The math module provides all the hyperbolic functions that appear in scientific and engineering applications, as follows:

Читайте также:  Web application html framework
Function Description
math.cosh(x) computes the hyperbolic cosine of x.
math.sinh(x) computes the hyperbolic sine of x.
math.tanh(x) computes the hyperbolic tangent of x.
math.acosh(x) computes the inverse hyperbolic cosine of x.
math.asinh(x) computes the inverse hyperbolic sine of x.
math.atanh(x) computes the inverse hyperbolic tangent of x.

Let’s do some calculations using the hyperbolic functions:

x = 0.5 print(math.cosh(x)) print(math.sinh(x)) print(math.tanh(x))
1.1276259652063807 0.5210953054937474 0.46211715726000974

Conclusion

The math built-in module includes a number of constants and methods that support mathematical operations from basic to advanced. We explored some of the most important and widely used constants and methods, including the number, power and logarithmic, trigonometric functions, and more.

Mehdi Lotfinejad

Mehdi is a Senior Data Engineer and Team Lead at ADA. He is a professional trainer who loves writing data analytics tutorials.

Источник

Python Math

Python has a set of built-in math functions, including an extensive math module, that allows you to perform mathematical tasks on numbers.

Built-in Math Functions

The min() and max() functions can be used to find the lowest or highest value in an iterable:

Example

x = min(5, 10, 25)
y = max(5, 10, 25)

The abs() function returns the absolute (positive) value of the specified number:

Example

The pow(x, y) function returns the value of x to the power of y (x y ).

Example

Return the value of 4 to the power of 3 (same as 4 * 4 * 4):

The Math Module

Python has also a built-in module called math , which extends the list of mathematical functions.

To use it, you must import the math module:

When you have imported the math module, you can start using methods and constants of the module.

The math.sqrt() method for example, returns the square root of a number:

Example

The math.ceil() method rounds a number upwards to its nearest integer, and the math.floor() method rounds a number downwards to its nearest integer, and returns the result:

Example

x = math.ceil(1.4)
y = math.floor(1.4)

print(x) # returns 2
print(y) # returns 1

The math.pi constant, returns the value of PI (3.14. ):

Example

Complete Math Module Reference

In our Math Module Reference you will find a complete reference of all methods and constants that belongs to the Math module.

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

Python math Module

Python has a built-in module that you can use for mathematical tasks.

Читайте также:  METANIT.COM

The math module has a set of methods and constants.

Math Methods

Method Description
math.acos() Returns the arc cosine of a number
math.acosh() Returns the inverse hyperbolic cosine of a number
math.asin() Returns the arc sine of a number
math.asinh() Returns the inverse hyperbolic sine of a number
math.atan() Returns the arc tangent of a number in radians
math.atan2() Returns the arc tangent of y/x in radians
math.atanh() Returns the inverse hyperbolic tangent of a number
math.ceil() Rounds a number up to the nearest integer
math.comb() Returns the number of ways to choose k items from n items without repetition and order
math.copysign() Returns a float consisting of the value of the first parameter and the sign of the second parameter
math.cos() Returns the cosine of a number
math.cosh() Returns the hyperbolic cosine of a number
math.degrees() Converts an angle from radians to degrees
math.dist() Returns the Euclidean distance between two points (p and q), where p and q are the coordinates of that point
math.erf() Returns the error function of a number
math.erfc() Returns the complementary error function of a number
math.exp() Returns E raised to the power of x
math.expm1() Returns E x — 1
math.fabs() Returns the absolute value of a number
math.factorial() Returns the factorial of a number
math.floor() Rounds a number down to the nearest integer
math.fmod() Returns the remainder of x/y
math.frexp() Returns the mantissa and the exponent, of a specified number
math.fsum() Returns the sum of all items in any iterable (tuples, arrays, lists, etc.)
math.gamma() Returns the gamma function at x
math.gcd() Returns the greatest common divisor of two integers
math.hypot() Returns the Euclidean norm
math.isclose() Checks whether two values are close to each other, or not
math.isfinite() Checks whether a number is finite or not
math.isinf() Checks whether a number is infinite or not
math.isnan() Checks whether a value is NaN (not a number) or not
math.isqrt() Rounds a square root number downwards to the nearest integer
math.ldexp() Returns the inverse of math.frexp() which is x * (2**i) of the given numbers x and i
math.lgamma() Returns the log gamma value of x
math.log() Returns the natural logarithm of a number, or the logarithm of number to base
math.log10() Returns the base-10 logarithm of x
math.log1p() Returns the natural logarithm of 1+x
math.log2() Returns the base-2 logarithm of x
math.perm() Returns the number of ways to choose k items from n items with order and without repetition
math.pow() Returns the value of x to the power of y
math.prod() Returns the product of all the elements in an iterable
math.radians() Converts a degree value into radians
math.remainder() Returns the closest value that can make numerator completely divisible by the denominator
math.sin() Returns the sine of a number
math.sinh() Returns the hyperbolic sine of a number
math.sqrt() Returns the square root of a number
math.tan() Returns the tangent of a number
math.tanh() Returns the hyperbolic tangent of a number
math.trunc() Returns the truncated integer parts of a number

Math Constants

Constant Description
math.e Returns Euler’s number (2.7182. )
math.inf Returns a floating-point positive infinity
math.nan Returns a floating-point NaN (Not a Number) value
math.pi Returns PI (3.1415. )
math.tau Returns tau (6.2831. )

Источник

Оцените статью