Math module modules python

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.

Источник

Numeric and Mathematical Modules¶

The modules described in this chapter provide numeric and math-related functions and data types. The numbers module defines an abstract hierarchy of numeric types. The math and cmath modules contain various mathematical functions for floating-point and complex numbers. The decimal module supports exact representations of decimal numbers, using arbitrary precision arithmetic.

Читайте также:  Accessing attributes in javascript

The following modules are documented in this chapter:

  • numbers — Numeric abstract base classes
    • The numeric tower
    • Notes for type implementors
      • Adding More Numeric ABCs
      • Implementing the arithmetic operations
      • Number-theoretic and representation functions
      • Power and logarithmic functions
      • Trigonometric functions
      • Angular conversion
      • Hyperbolic functions
      • Special functions
      • Constants
      • Conversions to and from polar coordinates
      • Power and logarithmic functions
      • Trigonometric functions
      • Hyperbolic functions
      • Classification functions
      • Constants
      • Quick-start Tutorial
      • Decimal objects
        • Logical operands
        • Mitigating round-off error with increased precision
        • Special values
        • Bookkeeping functions
        • Functions for bytes
        • Functions for integers
        • Functions for sequences
        • Real-valued distributions
        • Alternative Generator
        • Notes on Reproducibility
        • Examples
        • Recipes
        • Averages and measures of central location
        • Measures of spread
        • Statistics for relations between two inputs
        • Function details
        • Exceptions
        • NormalDist objects
          • NormalDist Examples and Recipes

          Источник

          Python math Module

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

          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. )

          Источник

          Модуль math

          Python 3 логотип

          Модуль math – один из наиважнейших в Python. Этот модуль предоставляет обширный функционал для работы с числами.

          math.ceil(X) – округление до ближайшего большего числа.

          math.copysign(X, Y) — возвращает число, имеющее модуль такой же, как и у числа X, а знак — как у числа Y.

          math.factorial(X) — факториал числа X.

          math.floor(X) — округление вниз.

          math.fmod(X, Y) — остаток от деления X на Y.

          math.frexp(X) — возвращает мантиссу и экспоненту числа.

          math.ldexp(X, I) — X * 2 i . Функция, обратная функции math.frexp().

          math.fsum(последовательность) — сумма всех членов последовательности. Эквивалент встроенной функции sum(), но math.fsum() более точна для чисел с плавающей точкой.

          math.isfinite(X) — является ли X числом.

          math.isinf(X) — является ли X бесконечностью.

          math.isnan(X) — является ли X NaN (Not a Number — не число).

          math.modf(X) — возвращает дробную и целую часть числа X. Оба числа имеют тот же знак, что и X.

          math.trunc(X) — усекает значение X до целого.

          math.expm1(X) — e X — 1. При X → 0 точнее, чем math.exp(X)-1.

          math.log(X, [base]) — логарифм X по основанию base. Если base не указан, вычисляется натуральный логарифм.

          math.log1p(X) — натуральный логарифм (1 + X). При X → 0 точнее, чем math.log(1+X).

          math.log10(X) — логарифм X по основанию 10.

          math.log2(X) — логарифм X по основанию 2.

          math.sqrt(X) — квадратный корень из X.

          math.acos(X) — арккосинус X. В радианах.

          math.asin(X) — арксинус X. В радианах.

          math.atan(X) — арктангенс X. В радианах.

          math.atan2(Y, X) — арктангенс Y/X. В радианах. С учетом четверти, в которой находится точка (X, Y).

          math.cos(X) — косинус X (X указывается в радианах).

          math.sin(X) — синус X (X указывается в радианах).

          math.tan(X) — тангенс X (X указывается в радианах).

          math.hypot(X, Y) — вычисляет гипотенузу треугольника с катетами X и Y (math.sqrt(x * x + y * y)).

          math.degrees(X) — конвертирует радианы в градусы.

          math.radians(X) — конвертирует градусы в радианы.

          math.cosh(X) — вычисляет гиперболический косинус.

          math.sinh(X) — вычисляет гиперболический синус.

          math.tanh(X) — вычисляет гиперболический тангенс.

          math.acosh(X) — вычисляет обратный гиперболический косинус.

          math.asinh(X) — вычисляет обратный гиперболический синус.

          math.atanh(X) — вычисляет обратный гиперболический тангенс.

          math.erf(X) — функция ошибок.

          math.erfc(X) — дополнительная функция ошибок (1 — math.erf(X)).

          math.gamma(X) — гамма-функция X.

          math.lgamma(X) — натуральный логарифм гамма-функции X.

          math.pi — pi = 3,1415926.

          Для вставки кода на Python в комментарий заключайте его в теги

          • Книги о Python
          • GUI (графический интерфейс пользователя)
          • Курсы Python
          • Модули
          • Новости мира Python
          • NumPy
          • Обработка данных
          • Основы программирования
          • Примеры программ
          • Типы данных в Python
          • Видео
          • Python для Web
          • Работа для Python-программистов

          Источник

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