Математические функции модуля math в Python
Модуль math является стандартным модулем в Python и всегда доступен. Чтобы использовать математические функции этого модуля, необходимо импортировать модуль с помощью import math . Например:
Этот модуль не поддерживает использование типа данных complex. Модуль cmath является аналогом модуля math, но уже с поддержкой типа complex.
Список функций модуля math в Python
Ниже приведен список всех функций и атрибутов, определенных в модуле math, с кратким объяснением того, что они делают.
Математические операции в Python: как вывести дробную часть и работать с числами
Представление чисел в Python 3 не отличается от обычных математических чисел. И поддерживают такие числа самые обыкновенные операции: сложение, вычитание, умножение, деление, возведение в степень, получение дробной части и т. п.
Целые числа (int)
Ниже вы можете увидеть стандартные Python-операции, в которых используется целое число (int):
a + b | Складываем |
a — b | Вычитаем |
a * b | Умножаем |
a / b | Делим |
a // b | Можем вывести целую часть от деления |
a % b | Можем вывести остаток от деления |
-a | Меняем знак числа |
abs(x) | Можем вывести модуль числа x |
divmod(a, b) | Пара (a // b, a % b) |
a ** b | Операция для возведения в степень |
pow(a, b[, x]) | ab по модулю (в случае, если модуль задан) |
Кроме того, числа int в Python 3 поддерживают длинную арифметику в отличие от некоторых других языков программирования. Однако для этого требуется больше памяти.
Битовые операции
Над числами int в Python можно выполнять и битовые операции. К примеру, a | b — это побитовое «или». Есть и другие варианты:
Дополнительные методы и операции в Python
В эти операции входят: • int.bit_length() — количество бит, которое необходимо, чтобы представить число в двоичном виде без учёта лидирующих нулей и знака; • int.to_bytes(length, byteorder, *, signed=False) — метод возвращает строку байтов, которые представляют это число; • classmethod int.from_bytes(bytes, byteorder, *, signed=False) — возвращение числа из заданной строки байтов.
Пример работы последнего метода:
Операции с системами счисления
Как гласит математика и информатика, числа можно представить как в десятичной, так и в двоичной системе счисления. Допустим, число 19 в двоичной системе имеет вид 10011. Также можно переводить числа из одной системы в другую. В Python для этого есть ряд функций: • int([object], [основание системы счисления]) — функция нужна для преобразования к целому числу. По умолчанию речь идёт о десятичной системе, однако можно задать любое основание в пределах чисел 2-36. • bin(x) — функция для преобразования целого числа в двоичную строку; • hex(х) — аналогично, но действительное целое число преобразуется в шестнадцатеричную строку; • oct(х) — для преобразования чисел в восьмеричную строку.
Операции с вещественными числами (float)
Чтобы вывести дробную часть, в Python используют вещественные числа. Они поддерживают выполнение тех же операций, что и в случае с int. Но из-за особенностей их представления в компьютере, когда выводишь дробную часть, возможны неточности и даже ошибки:
Для повышения точности операций используются такие объекты, как Decimal и Fraction.
Вспомогательные методы
К ним относят:
• float.as_integer_ratio() — это пара целых чисел int, отношение которых равно этому числу; • float.is_integer() — функция определят, является ли данное значение целым числом; • float.hex() — функция переводит float в 16-тиричную систему счисления, то есть в hex; • classmethod float.fromhex(s) — функцию используют для получения float из 16-тиричной строки.
Кроме стандартных выражений, в Python есть и специальные полезные модули. Например, модуль math позволяет выполнять более сложные арифметические функции:
А вот модуль random запускает генератор случайных чисел, позволяя реализовать функции случайного выбора:
Комплексные числа в Python (complex)
Также в Python встроены комплексные числа:
Кроме того, для работы с complex может применяться модуль cmath.
На этом пока что всё. Следите за новостями и не забывайте оставлять свои комментарии!
Покоряем Python — уроки для начинающих
Совсем недавно, был наглядно рассмотрен такой тип данных как числа. В данном посте мы рассмотрим как можно болше возможностей работы с числами. Смотрим ниже:
К примеру создадим переменные которые содержат в себе число:
>>>a=3
>>>b=4
Далее будем производить над ними какието действия:
>>>a + 1, a — 1 #сложение (3+1), вычитание (3-1)
(4, 2)
>>>b * 3, b / 2 # умножение, деление
(12, 2.0)
>>>a % 2,b ** 2 # деление по модулю, возведение в степень
(1, 16)
>>>2 + 4.0, 2.0 ** b # смешивание типов.
(6.0, 16.0)
>>> b / 2 + a # ((4 / 2) + 3)
5.0
>>>print(b/(2.0+a)) # (4 / (2.0 + 3))
0.8
>>> num = 1 / 3.0
>>> num # Автоматический вывод
0.33333333333333331
>>> print num # Инструкция print выполняет округление
0.333333333333
>>> “%e” % num # Вывод с использованием выражения форматирования строк
‘3.333333e-001’
>>> ‘%4.2f’ % num # Альтернативный формат представления вещественных чисел
‘0.33’
>>> ‘<0:4.2f>’.format(num) # Метод форматирования строк (Python 2.6 и 3.0)
‘0.33’
>>> num = 1 / 3
>>> repr(num) # Используется для автоматического вывода: в форме как есть
‘0.33333333333333331’
>>> str(num) # Используется функцией print: дружественная форма
‘0.333333333333’
>>> 1 < 2 # Меньше чем
True
>>> 2.0 >= 1 # Больше или равно: число 1 преобразуется 1.0
True
>>> 2.0 == 2.0 # Проверка на равенство значений
True
>>> 2.0 != 2.0 # Проверка на неравенство значений
False
How to truncate float values?
I want to remove digits from a float to have a fixed number of digits after the dot, like:
I need to output as a string to another function, not print.
Also I want to ignore the lost digits, not round them.
32 Answers 32
See Python’s documentation on the standard types. You’ll need to scroll down a bit to get to the round function. Essentially the second number says how many decimal places to round it to.
First, the function, for those who just want some copy-and-paste code:
This is valid in Python 2.7 and 3.1+. For older versions, it’s not possible to get the same «intelligent rounding» effect (at least, not without a lot of complicated code), but rounding to 12 decimal places before truncation will work much of the time:
Explanation
The core of the underlying method is to convert the value to a string at full precision and then just chop off everything beyond the desired number of characters. The latter step is easy; it can be done either with string manipulation
or the decimal module
The first step, converting to a string, is quite difficult because there are some pairs of floating point literals (i.e. what you write in the source code) which both produce the same binary representation and yet should be truncated differently. For example, consider 0.3 and 0.29999999999999998. If you write 0.3 in a Python program, the compiler encodes it using the IEEE floating-point format into the sequence of bits (assuming a 64-bit float)
This is the closest value to 0.3 that can accurately be represented as an IEEE float. But if you write 0.29999999999999998 in a Python program, the compiler translates it into exactly the same value. In one case, you meant it to be truncated (to one digit) as 0.3 , whereas in the other case you meant it to be truncated as 0.2 , but Python can only give one answer. This is a fundamental limitation of Python, or indeed any programming language without lazy evaluation. The truncation function only has access to the binary value stored in the computer’s memory, not the string you actually typed into the source code. 1
If you decode the sequence of bits back into a decimal number, again using the IEEE 64-bit floating-point format, you get
so a naive implementation would come up with 0.2 even though that’s probably not what you want. For more on floating-point representation error, see the Python tutorial.
It’s very rare to be working with a floating-point value that is so close to a round number and yet is intentionally not equal to that round number. So when truncating, it probably makes sense to choose the «nicest» decimal representation out of all that could correspond to the value in memory. Python 2.7 and up (but not 3.0) includes a sophisticated algorithm to do just that, which we can access through the default string formatting operation.
The only caveat is that this acts like a g format specification, in the sense that it uses exponential notation ( 1.23e+4 ) if the number is large or small enough. So the method has to catch this case and handle it differently. There are a few cases where using an f format specification instead causes a problem, such as trying to truncate 3e-10 to 28 digits of precision (it produces 0.0000000002999999999999999980 ), and I’m not yet sure how best to handle those.
If you actually are working with float s that are very close to round numbers but intentionally not equal to them (like 0.29999999999999998 or 99.959999999999994), this will produce some false positives, i.e. it’ll round numbers that you didn’t want rounded. In that case the solution is to specify a fixed precision.
The number of digits of precision to use here doesn’t really matter, it only needs to be large enough to ensure that any rounding performed in the string conversion doesn’t «bump up» the value to its nice decimal representation. I think sys.float_info.dig + n + 2 may be enough in all cases, but if not that 2 might have to be increased, and it doesn’t hurt to do so.
In earlier versions of Python (up to 2.6, or 3.0), the floating point number formatting was a lot more crude, and would regularly produce things like
If this is your situation, if you do want to use «nice» decimal representations for truncation, all you can do (as far as I know) is pick some number of digits, less than the full precision representable by a float , and round the number to that many digits before truncating it. A typical choice is 12,
but you can adjust this to suit the numbers you’re using.
1 Well. I lied. Technically, you can instruct Python to re-parse its own source code and extract the part corresponding to the first argument you pass to the truncation function. If that argument is a floating-point literal, you can just cut it off a certain number of places after the decimal point and return that. However this strategy doesn’t work if the argument is a variable, which makes it fairly useless. The following is presented for entertainment value only:
Generalizing this to handle the case where you pass in a variable seems like a lost cause, since you’d have to trace backwards through the program’s execution until you find the floating-point literal which gave the variable its value. If there even is one. Most variables will be initialized from user input or mathematical expressions, in which case the binary representation is all there is.