Как найти модуль от числа в python

{“id”:13943,”url”:”/distributions/13943/click?bit=1&hash=fa1a68c0b374f03ef7c98a801a20c4fde732f5ad4316b0bd53bd0cea0bb7d159″,”title”:”u041au0430u043a u043fu0440u043eu0434u0432u0438u0433u0430u0442u044c u0431u0440u0435u043du0434u044b u0438 u0442u043eu0432u0430u0440u044b u0432 u044du043fu043eu0445u0443 u043cu0430u0440u043au0435u0442u043fu043bu0435u0439u0441u043eu0432″,”buttonText”:””,”imageUuid”:””}

Вступление

Всем начинающим кодерам привет!

Модуль числа… Это, казалось бы, простая вещь… да, так оно и есть. Тем не менее – всегда интересно поэкспериментировать и по-новому взглянуть на простое.

Сегодня я покажу вам 6 способов найти модуль числа в Python 3. Я не стал добавлять сюда совсем абсурдные вещи, но немного абсурдности здесь все же будет.

1 способ

Для начала самое очевидное. Проверяем отрицательное число (назовем его x) или положительное, т.е. <0 или нет. В случае отрицательного значения x, его нужно умножить на -1. Можно так:

def abs1(x):
if x < 0:
return x*(-1)
return x

А можно заменить умножение унарным минусом:

def abs1(x):
if x < 0:
return -x
return x

2 способ

Самое короткое решение в нашей статье – найти максимум между x и -x. Таким образом результат всегда будет положительным:

def abs2(x):
return max(-x, x)

3 способ

Здесь мы проверяем строку на наличие в ней минуса. Изначально я хотел использовать метод isdigit(), но потом я понял, что метод не считает точку частью числа, поэтому для float в строке метод возвращает False. Поэтому:

​def abs3(x):
if ‘-‘ in str(x):
return -x
return x

4 способ

Этот способ использует условную инструкцию из предыдущей функции, но использует срез, чтобы избавиться от минуса. 3 строка выглядит не очень, приходится дважды менять тип данных результата. По-моему – это ухудшенная версия 3 способа:

def abs4(x):
if ‘-‘ in str(x):
return float(str(x)[1::])
return x

5 способ

Тут мы будем использовать факт того, что операция квадратного корня в Python всегда возвращает положительный результат. Эту операцию не обязательно брать из библиотеки Math, можно просто возвести число в с степень 0.5. Итак:

def abs5(x):
return (x*x)**0.5

6 способ

Здесь мы используем операции со строками, как в 4 способе. Отличие в том, что мы не проверяем строку на наличие минуса. Мы убираем уго, есть он в строке или нет. Метод replace() позволяет убрать все повторения одного символа, что для нас избыточно, но с нулем повторений он тоже работает:

def abs6(x):
return float(str(x).replace(‘-‘, ”))

Примечание: говоря про положительные значения, правильнее сказать – положительные или нулевые, но я решил не засорять текст такой мелочью.

Статистика быстродействия

Подведем итоги, узнаем – что же быстрее работает. О том, как замерить время работы программы, я, возможно, расскажу в одной из следующих статей. Ну а пока что приведу статистические данные.

Я измерил время работы данного куска кода, где i – одна из 6 функций.

for j in range(100000):
a = (i(1), i(-1), i(1.0), i(-1.0))

И вот что получилось:

Что у нас по итогу? Худший результат показал 4 способ, неудивительно.Самый очевидный способ – первый, на 2 месте. С большим отрывом лидирует 5 вариант, 100000 повторений за 0.79 сек! Математика быстрее логического оператора if и операций со строками.

Заключение

Я надеюсь, что вам была интересна данная статья, и вы разобрались в теме. Если хотите меня дополнить – пишите в комментариях. Удачи в мире IT!

Встроенная функция abs(x) в Python возвращает абсолютное значение аргумента x, который может быть целым или числом с плавающей точкой, или же объектом, реализующим функцию __abs__(). Для комплексных чисел функция возвращает их величину. Абсолютное значение любого числового значения -x или +x — это всегда соответствующее положительное +x.

Аргумент x целое число, число с плавающей точкой, комплексное число,
объект, реализующий __abs__()
Возвращаемое
значение
|x| возвращает абсолютное значение входящего аргумента

Следующий код демонстрирует, как получить абсолютное значение 42 положительного числа 42.

x = 42
abs_x = abs(x)
print(f"Абсолютное значение {x} это {abs_x}")
# Вывод: Абсолютное значение 42 это 42

Вывод: «Абсолютное значение 42 это 42».

То же самое, но уже с отрицательным -42.

x = -42
abs_x = abs(x)
print(f"Абсолютное значение {x} это {abs_x}")
#  Вывод: Абсолютное значение -42 это 42

Пример с числом float

Вот как получить абсолютное значение 42.42 и для -42.42:

x = 42.42
abs_x = abs(x)
print(f"Абсолютное значение {x} это {abs_x}")
#  Абсолютное значение 42.42 это 42.42

x = -42.42
abs_x = abs(x)
print(f"Абсолютное значение {x} это {abs_x}")
#  Абсолютное значение -42.42 это 42.42

Комплексное число

Абсолютное значение комплексного числа (3+10j).

complex_number = (3+10j)
abs_complex_number = abs(complex_number)
print(f"Абсолютное значение {complex_number} это {abs_complex_number}")
#  Абсолютное значение (3+10j) это 10.44030650891055

abs() vs fabs()

abs(x) вычисляет абсолютное значение аргумента x. По аналогии функция fabs(x) модуля math вычисляет то же значение. Разница лишь в том, что math.fabs(x) возвращает число с плавающей точкой, а abs(x) вернет целое число, если в качестве аргумента было целое число. Fabs расшифровывается как float absolute value.

Пример c fabs():

x = 42
print(abs(x))
# 42

import math
print(math.fabs(x))
# 42.0

abs() vs. np.abs()

И abs() в Python, и np.abs() в NumPy вычисляют абсолютное значение числа, но есть два отличия. np.abs(x) всегда возвращает число с плавающей точкой. Также np.abs(x) принимает массив NumPy, вычисляя значение для каждого элемента коллекции.

Пример:

x = 42
print(abs(x))
# 42

import numpy as np
print(np.fabs(x))
# 42.0

a = np.array([-1, 2, -4])
print(np.abs(a))
# [1 2 4]

abs и np.abs абсолютно идентичны. Нет разницы какой использовать. У первой преимущество лишь в том, что ее вызов короче.

Вывод

Функция abs() — это встроенная функция, возвращающая абсолютное значение числа. Она принимает целые, с плавающей точкой и комплексные числа на вход.

Если передать в abs() целое число или число с плавающей точкой, то функция вернет не-отрицательное значение n и сохранит тип. Для целого числа — целое число. Для числа с плавающей точкой — число с плавающей точкой.

>>> abs(20)
20
>>> abs(20.0)
20.0
>>> abs(-20.0)
20.0

Комплексные числа состоят из двух частей и могут быть записаны в форме a + bj, где a и b — это или целые числа, или числа с плавающей точкой. Абсолютное значение a + bj вычисляется математически как math.sqrt(a**2 + b**2).

>>> abs(3 + 4j)
5.0
>>> math.sqrt(3**2 + 4**2)
5.0

Таким образом, результат всегда положительный и всегда является числом с плавающей точкой.

Absolute values are commonly used in mathematics, physics, and engineering. Although the school definition of an absolute value might seem straightforward, you can actually look at the concept from many different angles. If you intend to work with absolute values in Python, then you’ve come to the right place.

In this tutorial, you’ll learn how to:

  • Implement the absolute value function from scratch
  • Use the built-in abs() function in Python
  • Calculate the absolute values of numbers
  • Call abs() on NumPy arrays and pandas series
  • Customize the behavior of abs() on objects

Don’t worry if your mathematical knowledge of the absolute value function is a little rusty. You’ll begin by refreshing your memory before diving deeper into Python code. That said, feel free to skip the next section and jump right into the nitty-gritty details that follow.

Defining the Absolute Value

The absolute value lets you determine the size or magnitude of an object, such as a number or a vector, regardless of its direction. Real numbers can have one of two directions when you ignore zero: they can be either positive or negative. On the other hand, complex numbers and vectors can have many more directions.

Consider a temperature measurement as an example. If the thermometer reads -12°C, then you can say it’s twelve degrees Celsius below freezing. Notice how you decomposed the temperature in the last sentence into a magnitude, twelve, and a sign. The phrase below freezing means the same as below zero degrees Celsius. The temperature’s size or absolute value is identical to the absolute value of the much warmer +12°C.

Using mathematical notation, you can define the absolute value of 𝑥 as a piecewise function, which behaves differently depending on the range of input values. A common symbol for absolute value consists of two vertical lines:

Absolute Value Defined as a Piecewise Function

Absolute Value Defined as a Piecewise Function

This function returns values greater than or equal to zero without alteration. On the other hand, values smaller than zero have their sign flipped from a minus to a plus. Algebraically, this is equivalent to taking the square root of a number squared:

Absolute Value Defined Algebraically

Absolute Value Defined Algebraically

When you square a real number, you always get a positive result, even if the number that you started with was negative. For example, the square of -12 and the square of 12 have the same value, equal to 144. Later, when you compute the square root of 144, you’ll only get 12 without the minus sign.

Geometrically, you can think of an absolute value as the distance from the origin, which is zero on a number line in the case of the temperature reading from before:

Absolute Value on a Number Line

Absolute Value on a Number Line

To calculate this distance, you can subtract the origin from the temperature reading (-12°C – 0°C = -12°C) or the other way around (0°C – (-12°C) = +12°C), and then drop the sign of the result. Subtracting zero doesn’t make much difference here, but the reference point may sometimes be shifted. That’s the case for vectors bound to a fixed point in space, which becomes their origin.

Vectors, just like numbers, convey information about the direction and the magnitude of a physical quantity, but in more than one dimension. For example, you can express the velocity of a falling snowflake as a three-dimensional vector:

This vector indicates the snowflake’s current position relative to the origin of the coordinate system. It also shows the snowflake’s direction and pace of motion through the space. The longer the vector, the greater the magnitude of the snowflake’s speed. As long as the coordinates of the vector’s initial and terminal points are expressed in meters, calculating its length will get you the snowflake’s speed measured in meters per unit of time.

The length of a vector, also known as its magnitude, is the distance between its initial and terminal points, 𝐴 and 𝐵, which you can calculate using the Euclidean norm:

The Length of a Bound Vector as a Euclidean Norm

The Length of a Bound Vector as a Euclidean Norm

This formula calculates the length of the 𝑛-dimensional vector 𝐴𝐵, by summing the squares of the differences between the coordinates of points 𝐴 and 𝐵 in each dimension indexed by 𝑖. For a free vector, the initial point, 𝐴, becomes the origin of the coordinate system—or zero—which simplifies the formula, as you only need to square the coordinates of your vector.

Recall the algebraic definition of an absolute value. For numbers, it was the square root of a number squared. Now, when you add more dimensions to the equation, you end up with the formula for the Euclidean norm, shown above. So, the absolute value of a vector is equivalent to its length!

All right. Now that you know when absolute values might be useful, it’s time to implement them in Python!

Implementing the Absolute Value Function in Python

To implement the absolute value function in Python, you can take one of the earlier mathematical definitions and translate it into code. For instance, the piecewise function may look like this:

def absolute_value(x):
    if x >= 0:
        return x
    else:
        return -x

You use a conditional statement to check whether the given number denoted with the letter x is greater than or equal to zero. If so, then you return the same number. Otherwise, you flip the number’s sign. Because there are only two possible outcomes here, you can rewrite the above function using a conditional expression that comfortably fits on a single line:

def absolute_value(x):
    return x if x >= 0 else -x

It’s exactly the same behavior as before, only implemented in a slightly more compact way. Conditional expressions are useful when you don’t have a lot of logic that goes into the two alternative branches in your code.

The algebraic definition of an absolute value is also pretty straightforward to implement in Python:

from math import sqrt

def absolute_value(x):
    return sqrt(pow(x, 2))

First, you import the square root function from the math module and then call it on the given number raised to the power of two. The power function is built right into Python, so you don’t have to import it. Alternatively, you can avoid the import statement altogether by leveraging Python’s exponentiation operator (**), which can simulate the square root function:

def absolute_value(x):
    return (x**2) ** 0.5

This is sort of a mathematical trick because using a fractional exponent is equivalent to computing the 𝑛th root of a number. In this case, you take a squared number to the power of one-half (0.5) or one over two (½), which is the same as calculating the square root. Note that both Python implementations based on the algebraic definition suffer from a slight deficiency:

>>>

>>> def absolute_value(x):
...     return (x**2) ** 0.5

>>> absolute_value(-12)
12.0

>>> type(12.0)
<class 'float'>

You always end up with a floating-point number, even if you started with an integer. So, if you’d like to preserve the original data type of a number, then you might prefer the piecewise-based implementation instead.

As long as you stay within integers and floating-point numbers, you can also write a somewhat silly implementation of the absolute value function by leveraging the textual representation of numbers in Python:

def absolute_value(x):
    return float(str(x).lstrip("-"))

You convert the function’s argument, x, to a Python string using the built-in str() function. This lets you strip the leading minus sign, if there is one, with an empty string. Then, you convert the result to a floating-point number with float(). Note this implementation always converts integers to floats.

Implementing the absolute value function from scratch in Python is a worthwhile learning exercise. However, in real-life applications, you should take advantage of the built-in abs() function that comes with Python. You’ll find out why in the next section.

Using the Built-in abs() Function With Numbers

The last function that you implemented above was probably the least efficient one because of the data conversions and the string operations, which are usually slower than direct number manipulation. But in truth, all of your hand-made implementations of an absolute value pale in comparison to the abs() function that’s built into the language. That’s because abs() is compiled to blazing-fast machine code, while your pure-Python code isn’t.

You should always prefer abs() over your custom functions. It runs much more quickly, an advantage that can really add up when you have a lot of data to process. Additionally, it’s much more versatile, as you’re about to find out.

Integers and Floating-Point Numbers

The abs() function is one of the built-in functions that are part of the Python language. That means you can start using it right away without importing:

>>>

>>> abs(-12)
12

>>> abs(-12.0)
12.0

As you can see, abs() preserves the original data type. In the first case, you passed an integer literal and got an integer result. When called with a floating-point number, the function returned a Python float. But these two data types aren’t the only ones that you can call abs() on. The third numeric type that abs() knows how to handle is Python’s complex data type, which represents complex numbers.

Complex Numbers

You can think of a complex number as a pair consisting of two floating-point values, commonly known as the real part and the imaginary part. One way to define a complex number in Python is by calling the built-in complex() function:

It accepts two arguments. The first one represents the real part, while the second one represents the imaginary part. At any point, you can access the complex number’s .real and .imag attributes to get those parts back:

>>>

>>> z.real
3.0

>>> z.imag
2.0

Both of them are read-only and are always expressed as floating-point values. Also, the absolute value of a complex number returned by abs() happens to be a floating-point number:

>>>

>>> abs(z)
3.605551275463989

This might surprise you until you find out that complex numbers have a visual representation that resembles two-dimensional vectors fixed at the coordinate system’s origin:

Complex Number as a Vector

You already know the formula to calculate the length of such a vector, which in this case agrees with the number returned by abs(). Note that the absolute value of a complex number is more commonly referred to as the magnitude, modulus, or radius of a complex number.

While integers, floating-point numbers, and complex numbers are the only numeric types supported natively by Python, you’ll find two additional numeric types in its standard library. They, too, can interoperate with the abs() function.

Fractions and Decimals

The abs() function in Python accepts all numeric data types available, including the lesser-known fractions and decimals. For instance, you can get the absolute value of one-third or minus three-quarters defined as Fraction instances:

>>>

>>> from fractions import Fraction

>>> abs(Fraction("1/3"))
Fraction(1, 3)

>>> abs(Fraction("-3/4"))
Fraction(3, 4)

In both cases, you get another Fraction object back, but it’s unsigned. That can be convenient if you plan to continue your computations on fractions, which offer higher precision than floating-point numbers.

If you’re working in finance, then you’ll probably want to use Decimal objects to help mitigate the floating-point representation error. Luckily, you can take the absolute value of these objects:

>>>

>>> from decimal import Decimal

>>> abs(Decimal("0.3333333333333333"))
Decimal('0.3333333333333333')

>>> abs(Decimal("-0.75"))
Decimal('0.75')

Again, the abs() function conveniently returns the same data type as the one that you supplied, but it gives you an appropriate positive value.

Wow, abs() can deal with an impressive variety of numeric data types! But it turns out that abs() is even more clever than that. You can even call it on some objects delivered by third-party libraries, as you’ll try out in the next section.

Calling abs() on Other Python Objects

Say you want to compute the absolute values of average daily temperature readings over some period. Unfortunately, as soon as you try calling abs() on a Python list with those numbers, you get an error:

>>>

>>> temperature_readings = [1, -5, 1, -4, -1, -8, 0, -7, 3, -5, 2]
>>> abs(temperature_readings)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: bad operand type for abs(): 'list'

That’s because abs() doesn’t know how to process a list of numbers. To work around this, you could use a list comprehension or call Python’s map() function, like so:

>>>

>>> [abs(x) for x in temperature_readings]
[1, 5, 1, 4, 1, 8, 0, 7, 3, 5, 2]

>>> list(map(abs, temperature_readings))
[1, 5, 1, 4, 1, 8, 0, 7, 3, 5, 2]

Both implementations do the job but require an additional step, which may not always be desirable. If you want to cut that extra step, then you may look into external libraries that change the behavior of abs() for your convenience. That’s what you’ll explore below.

NumPy Arrays and pandas Series

One of the most popular libraries for extending Python with high-performance arrays and matrices is NumPy. Its 𝑛-dimensional array data structure, ndarray, is the cornerstone of numerical computing in Python, so many other libraries use it as a foundation.

Once you convert a regular Python list to a NumPy array with np.array(), you’ll be able to call some of the built-in functions, including abs(), on the result:

>>>

>>> import numpy as np
>>> temperature_readings = np.array([1, -5, 1, -4, -1, -8, 0, -7, 3, -5, 2])
>>> abs(temperature_readings)
array([1, 5, 1, 4, 1, 8, 0, 7, 3, 5, 2])

In response to calling abs() on a NumPy array, you get another array with the absolute values of the original elements. It’s as if you iterated over the list of temperature readings yourself and applied the abs() function on each element individually, just as you did with a list comprehension before.

You can convert a NumPy array back to a Python list if you find that more suitable:

>>>

>>> list(abs(temperature_readings))
[1, 5, 1, 4, 1, 8, 0, 7, 3, 5, 2]

However, note that NumPy arrays share most of the Python list interface. For example, they support indexing and slicing, and their methods are similar to those of plain lists, so most people usually just stick to using NumPy arrays without ever looking back at lists.

pandas is another third-party library widely used in data analysis thanks to its Series and DataFrame objects. A series is a sequence of observations or a column, whereas a DataFrame is like a table or a collection of columns. You can call abs() on both of them.

Suppose you have a Python dictionary that maps a city name to its lowest average temperatures observed monthly over the course of a year:

>>>

>>> lowest_temperatures = {
...     "Reykjavxedk": [-3, -2, -2, 1, 4, 7, 9, 8, 6, 2, -1, -2],
...     "Rovaniemi": [-16, -14, -10, -3, 3, 8, 12, 9, 5, -1, -6, -11],
...     "Valetta": [9, 9, 10, 12, 15, 19, 21, 22, 20, 17, 14, 11],
... }

Each city has twelve temperature readings, spanning from January to December. Now, you can turn that dictionary into a pandas DataFrame object so that you can draw some interesting insights going forward:

>>>

>>> import calendar
>>> import pandas as pd

>>> df = pd.DataFrame(lowest_temperatures, index=calendar.month_abbr[1:])
>>> df
     Reykjavík  Rovaniemi  Valetta
Jan         -3        -16        9
Feb         -2        -14        9
Mar         -2        -10       10
Apr          1         -3       12
May          4          3       15
Jun          7          8       19
Jul          9         12       21
Aug          8          9       22
Sep          6          5       20
Oct          2         -1       17
Nov         -1         -6       14
Dec         -2        -11       11

Instead of using the default zero-based index, your DataFrame is indexed by abbreviated month names, which you obtained with the help of the calendar module. Each column in the DataFrame has a sequence of temperatures from the original dictionary, represented as a Series object:

>>>

>>> df["Rovaniemi"]
Jan   -16
Feb   -14
Mar   -10
Apr    -3
May     3
Jun     8
Jul    12
Aug     9
Sep     5
Oct    -1
Nov    -6
Dec   -11
Name: Rovaniemi, dtype: int64

>>> type(df["Rovaniemi"])
<class 'pandas.core.series.Series'>

By using the square bracket ([]) syntax and a city name like Rovaniemi, you can extract a single Series object from the DataFrame and narrow down the amount of information displayed.

pandas, just like NumPy, lets you call many of Python’s built-in functions on its objects, including its DataFrame and Series objects. Specifically, you can call abs() to calculate more than one absolute value in one go:

>>>

>>> abs(df)
     Reykjavík  Rovaniemi  Valetta
Jan          3         16        9
Feb          2         14        9
Mar          2         10       10
Apr          1          3       12
May          4          3       15
Jun          7          8       19
Jul          9         12       21
Aug          8          9       22
Sep          6          5       20
Oct          2          1       17
Nov          1          6       14
Dec          2         11       11

>>> abs(df["Rovaniemi"])
Jan    16
Feb    14
Mar    10
Apr     3
May     3
Jun     8
Jul    12
Aug     9
Sep     5
Oct     1
Nov     6
Dec    11
Name: Rovaniemi, dtype: int64

Calling abs() on the entire DataFrame applies the function to each element in every column. You can also call abs() on the individual column.

How did NumPy and pandas change the behavior of Python’s built-in abs() function without modifying its underlying code? Well, it was possible because the function was designed with such extensions in mind. If you’re looking for an advanced use of abs(), then read on to make your own data type that’ll play nicely with that function.

Your Very Own Data Types

Depending on the data type, Python will handle the computation of absolute values differently.

When you call abs() on an integer, it’ll use a custom code snippet that resembles your piecewise function. However, that function will be implemented in the C programming language for efficiency. If you pass a floating-point number, then Python will delegate that call to C’s fabs() function. In the case of a complex number, it’ll call the hypot() function instead.

What about container objects like DataFrames, series, and arrays?

Understandably, when you define a new data type in Python, it won’t work with the abs() function because its default behavior is unknown. However, you can optionally customize the behavior of abs() against the instances of your class by implementing the special .__abs__() method using pure Python. There’s a finite set of predefined special methods in Python that let you override how certain functions and operators should work.

Consider the following class representing a free 𝑛-dimensional vector in the Euclidean space:

>>>

>>> import math

>>> class Vector:
...     def __init__(self, *coordinates):
...         self.coordinates = coordinates
...
...     def __abs__(self):
...         origin = [0] * len(self.coordinates)
...         return math.dist(origin, self.coordinates)

This class accepts one or more coordinate values, describing the displacement in each dimension from the origin of the coordinate system. Your special .__abs__() method calculates the distance from the origin, according to the Euclidean norm definition that you learned at the beginning of this tutorial.

To test your new class, you can create a three-dimensional velocity vector of a falling snowflake, for example, which might look like this:

>>>

>>> snowflake_velocity = Vector(0.42, 1.5, 0.87)
>>> abs(snowflake_velocity)
1.7841804841439108

Notice how calling abs() on your Vector class instance returns the correct absolute value, equal to about 1.78. The speed units will be expressed in meters per second as long as the snowflake’s displacement was measured in meters at two distinct time instants one second apart. In other words, it would take one second for the snowflake to travel from point A to point B.

Using the mentioned formula forces you to define the origin point. However, because your Vector class represents a free vector rather than a bound one, you can simplify your code by calculating the multidimensional hypotenuse using Python’s math.hypot() function:

>>>

>>> import math

>>> class Vector:
...     def __init__(self, *coordinates):
...         self.coordinates = coordinates
...
...     def __abs__(self):
...         return math.hypot(*self.coordinates)

>>> snowflake_velocity = Vector(0.42, 1.5, 0.87)
>>> abs(snowflake_velocity)
1.7841804841439108

You get the same result with fewer lines of code. Note that hypot() is a variadic function accepting a variable number of arguments, so you must use the star operator (*) to unpack your tuple of coordinates into those arguments.

Awesome! You can now implement your own library, and Python’s built-in abs() function will know how to work with it. You’ll get functionality similar to working with NumPy or pandas!

Conclusion

Implementing formulas for an absolute value in Python is a breeze. However, Python already comes with the versatile abs() function, which lets you calculate the absolute value of various types of numbers, including integers, floating-point numbers, complex numbers, and more. You can also use abs() on instances of custom classes and third-party library objects.

In this tutorial, you learned how to:

  • Implement the absolute value function from scratch
  • Use the built-in abs() function in Python
  • Calculate the absolute values of numbers
  • Call abs() on NumPy arrays and pandas series
  • Customize the behavior of abs() on objects

With this knowledge, you’re equipped with an efficient tool to calculate absolute values in Python.

  • Модуль числа

  • Вычисление

  • abs

  • fabs

  • Свое решение

  • Модуль комплексного числа

Очень часто возникает необходимость вычисления модуля числа в Python. Рассмотрим, что такое модуль числа, какие есть способы его вычисления. Так же отдельно коснемся комплексных чисел.

Модуль числа

Часто в программировании требуется вычислить абсолютное значение числа. Иначе говоря, отбросить знак.

При вычислении модуля возможны 3 ситуации:

  • Когда число больше 0. Если взять его по модулю — не изменится.
  • Модуль нуля так же равен нулю.
  • У отрицательного числа отбрасываем знак. То есть умножаем его на -1.

Но это все справедливо только для действительных чисел. Чему же тогда будет равен модуль комплексных?

Комплексное число состоит из действительной составляющей и мнимой. Геометрически это можно представить как 2 ортогональные оси: действительную и мнимую. Отмечаем на координатных осях требуемую точку. Модулем будет длина отрезка, проведенного из начала координат в эту точку.

Исходя из теоремы Пифагора получаем, что модуль комплексного числа это корень квадратный из суммы квадратов мнимой и действительной частей.

Вычисление

Вычислять модуль можно следующими способами:

  • Используя стандартную функцию abs.
  • С помощью функции fabs библиотеки math.
  • При помощи самостоятельно написанной функции.

Все эти функции работают как в Python 2, так и в Python 3.

abs

Для вычисления в Python модуля числа используется функция abs. Результат функции того же типа, которого был аргумент.

a = -10
b = abs(a)
print(b)
print(type(b))

10
<class 'int'>

fabs

Можно так же воспользоваться функцией fabs из библиотеки math. Библиотеку можно подключить с помощью from math import fabs.

from math import fabs
a = -10
b = fabs(a)
print(b)
print(type(b))

10.0
<class 'float'>

Отличие abs от fabs заключается в том, что функция abs возвращает значение того же типа, что и аргумент. Функция же fabs вначале преобразует тип аргумента к вещественному числу.

Свое решение

Если по каким то причинам нет возможности или желания использовать стандартные функции, то можно написать свое решение.

Например, можно вычислить воспользоваться тернарным оператором.

a = -10
b = a if a > 0 else -a
print(b)

10

На основе такого условия сделаем свою функцию.

def my_abs(a):
    return a if a > 0 else -a
print(my_abs(-3))

3

Модуль комплексного числа

Мы разобрались как происходит вычисление с действительными числами. Теперь посмотрим, как в языке программирования Python можно получить модуль комплексного.

Функцией fabs мы не сможем воспользоваться. Если попытаемся это сделать, то получим ошибку приведения комплексного числа к действительному (TypeError).

from math import fabs
a = -10-2j
b = fabs(a)
print(b)

Traceback (most recent call last):
  File "main.py", line 3, in <module>
    b = fabs(a)
TypeError: can't convert complex to float

А вот с помощью abs преобразование удается.

a = -10-2j
b = abs(a)
print(b)

10.19803902718557

Или же напишем свою функцию:

from math import sqrt
def my_abs_complex(c):
    return sqrt(c.real**2 + c.imag**2)
a = -10-2j
b = my_abs_complex(a)
print(b)

10.198039027185569

Результаты получились одинаковыми. Но нам все равно пришлось подключить библиотеку math для вычисления квадратного корня.

The Python abs() function return the absolute value and remove the negative sign of a number in Python.  

Python abs() Function Syntax

Syntax: abs(number)

  • number: Integer, floating-point number, complex number.

Return: Returns the absolute value.

Python abs() Function Example

Python abs() Function with int in Python.

Python3

var = -94

print('Absolute value of integer is:', abs(var))

Output:

94

Example 1: Get the absolute value of a number

In this example, we pass int data into the abs() function and it will return an absolute value.

Python3

var = -100

print('Absolute value of integer is:', abs(var))

Output: 

Absolute value of integer is: 100

Example 2: Get the absolute value of a floating  number

In this example, we pass float data into the abs() function and it will return an absolute value.

Python3

float_number = -54.26

print('Absolute value of float is:'

                  abs(float_number))

Output: 

Absolute value of float is: 54.26

Example 3: Get the absolute value of a complex number

In this example, we pass Python complex data into the abs() function and it will return an absolute value.

Python3

complex_number = (3 - 4j)

print('Absolute value or Magnitude of complex is:', abs(complex_number))

Output: 

Absolute value or Magnitude of complex is: 5.0

Example 4: Time-Distance calculation using Python abs()

This equation shows the relationship between speed, distance traveled and time taken and we know speed, time and distance are never negative, for this, we will use abs() methods to calculate the exact time, distance, and speed.

Formula used:  

Distance  = Speed * Time

Time = Distance / Speed

Speed = Distance / Time

Python3

def cal_speed(dist, time):

    print(" Distance(km) :", dist)

    print(" Time(hr) :", time)

    return dist / time

def cal_dis(speed, time):

    print(" Time(hr) :", time)

    print(" Speed(km / hr) :", speed)

    return speed * time

def cal_time(dist, speed):

    print(" Distance(km) :", dist)

    print(" Speed(km / hr) :", speed)

    return speed * dist

print(" The calculated Speed(km / hr) is :",

      cal_speed(abs(45.9), abs(2.0)))

print("")

print(" The calculated Distance(km) :",

      cal_dis(abs(62.9), abs(2.5)))

print("")

print(" The calculated Time(hr) :",

      cal_time(abs(48.0), abs(4.5)))

Output:

 Distance(km) : 45.9
 Time(hr) : 2.0
 The calculated Speed(km / hr) is : 22.95

 Time(hr) : 2.5
 Speed(km / hr) : 62.9
 The calculated Distance(km) : 157.25

 Distance(km) : 48.0
 Speed(km / hr) : 4.5
 The calculated Time(hr) : 216.0

Time Complexity:  O(1)

Auxiliary Space: O(1)

Last Updated :
25 Jul, 2022

Like Article

Save Article

Добавить комментарий