Math in python examples

Python Math Module: A Complete Guide (Examples)

If you need anything more complex than the basic arithmetic operators in Python, there’s a built-in library called Math you can use.

With this module, you can calculate square roots, medians, distances, and such.

This guide teaches you how to start using the math module in Python.

To start using the module in your project, you need to import it first.

Common Math Module Operations in Python

Some common math module operations you are going to see a lot are:

Let’s go through each of these.

How to Find the Square Root of a Number in Python

Square root answers the question: “What number squared gives this number?”.

Читайте также:  Java design patterns pdf head first

In Python, you can find the square root of a number using the math module’s sqrt() function.

number = 16 square_rooted = math.sqrt(number) print(square_rooted)

How to Round Numbers in Python

To round numbers in Python, use the built-in round() function. (This is not part of the math module, but it fits well here, because of the following sections.)

The round function takes two arguments:

For example, let’s round a decimal to two decimal places:

How to Round Numbers Down in Python

To round a number down to its nearest integer value, use the math module’s floor() function.

number = 3.9 floored = math.floor(number) print(floored)

How to Round Numbers Up in Python

To round a number up to its nearest integer value, use the math module’s ceil() function.

number = 3.1 ceiled = math.ceil(number) print(ceiled)

Trigonometry with the Math Module in Python

The math module is useful because in addition to the basic operations you saw above, you can do basic trigonometry with it. These involve dealing with angles and distances.

Pi Constant in Python

Pi is probably the most famous number in mathematics. It is the ratio of the circumference of any circle to the diameter of that circle.

You can access the value of π via the math module:

How to Calculate Distance in Python

Python maths distance function

To calculate the (Euclidian) distance between two points, use the math.dist() function.

For example, let’s calculate the distance between origin and point (1, 1) in a 2D coordinate system:

origin = (0, 0) p1 = (1, 1) distance = math.dist(origin, p1) print(distance)

Notice you can compute the distance in any other dimension too.

How to Convert Degrees to Radians in Python

To convert degrees to radians, use the math.degrees() function.

For example, let’s convert 2π radians to degrees:

rads = 2 * math.pi degs = math.degrees(rads) print(degs)

How to Convert Radians to Degrees in Python

To convert radians to degrees, use the math.radians() function.

For example, let’s convert 180 degrees to radians:

degs = 180.0 rads = math.radians(degs) print(rads)

Sin in Python

Python maths sine function

To calculate the sine of an angle, use the math.sin() function. Notice this function assumes your angle is in radians. If you’re using degrees, remember to convert the degrees to radians with math.radians() function.

degs = 45.0 rads = math.radians(degs) print(math.sin(rads))

Arc Sin in Python

To get an angle given a fraction, you can use the math.asin() function.

ratio = 0.7071067811865475 rads = math.asin(ratio) degrees = math.degrees(rads) print(degrees)

This value should be exactly 45, but due to floating-point accuracy, you might see a value really close to that.

Cos in Python

Python maths cosine function

To calculate the cosine of an angle, use the math.cos() function.

This function assumes your angle is in radians. If you’re using degrees, remember to convert the degrees to radians with math.radians() function.

degs = 30.0 rads = math.radians(degs) print(math.cos(rads))

Arc Cos in Python

To get an angle given a fraction, you can use the math.acos() function.

ratio = 0.8660254037844387 rads = math.acos(ratio) degrees = math.degrees(rads) print(degrees)

This value should be exactly 30, but due to floating-point accuracy, you might see a value really close to that.

Tan in Python

Python maths tangent function

To calculate the tangent of an angle, use the math.tan() function.

This function assumes your angle is in radians. If you’re using degrees, remember to convert the degrees to radians with math.radians() function.

degs = 75.0 rads = math.radians(degs) print(math.tan(rads))

Arc Tan in Python

To get an angle given a fraction, you can use the math.atan() function.

ratio = 3.7320508075688776 rads = math.atan(ratio) degrees = math.degrees(rads) print(degrees)

Conclusion

Now you know the basics of maths with Python.

Python natively supports 7 arithmetic operations: addition, subtraction, multiplication, division, floor division, exponentiation, and modulus.

To perform more common maths operations in Python, use the math module by importing it to your project.

Thanks for reading. I hope you find it useful.

Источник

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.

Источник

Модуль Math в Python

Python библиотека math содержит наиболее применяемые математические функции и константы. Все вычисления происходят на множестве вещественных чисел.

Если вам нужен соответствующий аппарат для комплексного исчисления, модуль math не подойдёт. Используйте вместо него cmath . Там вы найдёте комплексные версии большинства популярных math -функций.

Синтаксис и подключение

Чтобы подключить модуль, необходимо в начале программы прописать следующую инструкцию:

Теперь с помощью точечной нотации можно обращаться к константам и вызывать функции этой библиотеки. Например, так:

Константы модуля Math

math.pi Представление математической константы π = 3.141592…. «Пи» — это отношение длины окружности к её диаметру.

math.e Число Эйлера или просто e . Иррациональное число, которое приблизительно равно 2,71828.

math.tau Число τ — это отношение длины окружности к её радиусу. Т.е

import math > print(math.tau) print(math.tau == 2 * math.pi) > True

math.inf Положительная бесконечность.

Для оперирования отрицательной бесконечно большой величиной, используйте -math.inf

Константа math.inf эквивалента выражению float(«inf») .

math.nan NaN означает — «не число».

Аналогичная запись: float(«nan») .

Список функций

Теоретико-числовые функции и функции представления

math.ceil() Функция округляет аргумент до большего целого числа.

math.comb(n, k) Число сочетаний из n по k . Показывает сколькими способами можно выбрать k объектов из набора, где находится n объектов. Формула:

Решим задачу : На столе лежат шесть рубинов. Сколько существует способов выбрать два из них?

💭 Можете подставить числа в формулу, и самостоятельно проверить правильность решения.

math.copysign() Функция принимает два аргумента. Возвращает первый аргумент, но со знаком второго.

math.fabs() Функция возвращает абсолютное значение аргумента:

math.factorial() Вычисление факториала. Входящее значение должно быть целочисленным и неотрицательным.

math.floor() Антагонист функции ceil() . Округляет число до ближайшего целого, но в меньшую сторону.

math.fmod(a, b) Считает остаток от деления a на b . Является аналогом оператора » % » с точностью до типа возвращаемого значения.

math.frexp(num) Возвращает кортеж из мантиссы и экспоненты аргумента. Формула:

, где M — мантисса, E — экспонента.

print(math.frexp(10)) > (0.625, 4) # проверим print(pow(2, 4) * 0.625) > 10.0

math.fsum() Вычисляет сумму элементов итерируемого объекта. Например, вот так она работает для списка:

summable_list = [1, 2, 3, 4, 5] print(math.fsum(summable_list)) > 15.0

math.gcd(a, b) Возвращает наибольший общий делитель a и b . НОД — это самое большое число, на которое a и b делятся без остатка.

a = 5 b = 15 print(math.gcd(a, b)) > 5

math.isclose(x, y) Функция возвращает True , если значения чисел x и y близки друг к другу, и False в ином случае. Помимо пары чисел принимает ещё два необязательных именованных аргумента:

  • rel_tol — максимально допустимая разница между числами в процентах;
  • abs_tol — минимально допустимая разница.

math.isfinite() Проверяет, является ли аргумент NaN , False или же бесконечностью. True , если не является, False — в противном случае.

norm = 3 inf = float(‘inf’) print(math.isfinite(norm)) > True print(math.isfinite(inf)) > False

math.isinf() True , если аргумент — положительная/отрицательная бесконечность. False — в любом другом случае.

not_inf = 42 inf = math.inf print(math.isinf(not_inf)) > False print(math.isinf(inf)) > True

math.isnan() Возврат True , если аргумент — не число ( nan ). Иначе — False .

not_nan = 0 nan = math.nan print(math.isnan(not_nan)) > False print(math.isnan(nan)) > True

math.isqrt() Возвращает целочисленный квадратный корень аргумента, округлённый вниз.

math.ldexp(x, i) Функция возвращает значение по формуле:

возвращаемое значение = x * (2 ** i) print(math.ldexp(3, 2)) > 12.0

math.modf() Результат работы modf() — это кортеж из двух значений:

math.perm(n, k) Возвращает число размещений из n по k . Формула:

Задача : Посчитать количество вариантов распределения трёх билетов на концерт Стаса Михайлова для пяти фанатов.

Целых 60 способов! Главное — не запутаться в них, и не пропустить концерт любимого исполнителя!

math.prod() Принимает итерируемый объект. Возвращает произведение элементов.

multiple_list = [2, 3, 4] print(math.prod(multiple_list)) > 24

math.remainder(m, n) Возвращает результат по формуле:

где x — ближайшее целое к выражению m/n число.

print(math.remainder(55, 6)) > 1.0 print(math.remainder(4, 6)) > -2.0

math.trunc() trunc() вернёт вам целую часть переданного в неё аргумента.

Степенные и логарифмические функции

math.exp(x) Возвращает e в степени x . Более точный аналог pow(math.e, x) .

print(math.exp(3)) > 20.085536923187668

math.expm1(x) Вычисляет значение выражения exp(x) — 1 и возвращает результат.

print(math.expm1(3)) > 19.085536923187668 print(math.expm1(3) == (math.exp(3) — 1)) > True

math.log() Функция работает, как с одним, так и с двумя параметрами .

1 аргумент: вернёт значение натурального логарифма (основание e ):

2 аргумента: вернёт значение логарифма по основанию, заданному во втором аргументе:

☝️ Помните, это читается, как простой вопрос: «в какую степень нужно возвести число 4 , чтобы получить 16 «. Ответ, очевидно, 2 . Функция log() с нами согласна.

math.log1p() Это натуральный логарифм от аргумента (1 + x) :

print(math.log(5) == math.log1p(4)) > True

math.log2() Логарифм по основанию 2 . Работает точнее, чем math.log(x, 2) .

math.log10() Логарифм по основанию 10 . Работает точнее, чем math.log(x, 10) .

math.pow(a, b) Функция выполняет возведение числа a в степень b и возвращает затем вещественный результат.

Источник

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