Abs python что значит

Python Absolute Value – Python abs Tutorial

Dionysia Lemonaki

Dionysia Lemonaki

Python Absolute Value – Python abs Tutorial

In this article, you will learn all about the abs() function in Python.

You will learn what the abs() function does and why you may want to use it.

You will also understand how to use abs() with the help of practical examples.

Here is what we will cover:

What is The abs() Function in Python?

The abs() built-in Python function returns the absolute value of a number.

But what is an absolute value of a number in the first place?

In mathematics, the absolute value of a number refers to that number’s distance from zero.

Essentially, it is how far away that number is from zero on the number line.

For example, the absolute value of the number five is five since the distance from zero to five is five units.

Screenshot-2022-06-14-at-9.51.34-AM

Something to take note of is that the absolute value will always be a positive value. So, when it comes to calculating the absolute value of a negative number, the result will always be the positive version of that number.

For example, the absolute value of negative five is also five:

Screenshot-2022-06-14-at-10.01.18-AM

Why Are Absolute Values Important?

Absolute values are an important concept and are commonly used in Math and Physics.

There may be times when you only need to use positive numbers and will not need to make use of any negative ones. In fact, you may need to make sure there are no negative numbers whatsoever for the calculations you are about to perform.

Читайте также:  Resource bundle java properties

You will most likely use absolute values for calculating the distance of one point to another.

Some other common real-world examples could be:

  • Calculating the difference between two points.
  • Calculating the amount of energy used.
  • Calculating the temperature, time, and speed differences between two points.

How to Use the abs() Function in Python? A Syntax Breakdown for Beginners

The general syntax for the abs() function looks something like this:

  • The abs() function takes only one single argument, which is required.
  • The argument is always a number which can have a negative or positive value.
  • The number can either be:
    • An integer, such as 4 , -15 , or 10 .
    • A floating-point number, such as 4.1 , -15.06 , or 2.13 .
    • A complex number. A complex number is made up of two parts — a real part which consists of a real number such as 1 or 4 , and an imaginary part. In Python, the imaginary part is created by adding the letter j as a suffix – not the letter i like it is in Mathematics. You add j to the end of a real number, like so: 1j or 4j .So, an example of a complex number in Python is 2 + 4j or 1 + 2j .

    Now, when it comes to the return value of the abs() function:

    • For integer numbers, the abs() function returns the absolute value of the given number.
    • For floating point numbers, the abs() function returns the absolute value of the given number.
    • For complex numbers, the abs() function returns the magnitude of the given number.

    How to Use the abs() Function with Examples

    In the following sections, you will see the abs() function in action and how it behaves when it has an integer, a floating-point number, and a complex number as an argument.

    How to Use the abs() Function with an Integer Argument

    When you pass an integer as an argument, the abs() function will return its absolute value.

    Below is an example of passing a positive integer as an argument:

    my_number = 7 abs_value = abs(my_number) print(abs_value) #output #7 

    And below is an example of passing a negative integer as an argument.

    Remember that the absolute value will always be positive:

    my_number = -17 abs_value = abs(my_number) print(abs_value) #output #17 

    How to Use the abs() Function with a Floating-Point Number Argument

    When you pass a floating-point number as an argument, the abs() function will return its absolute value.

    The following examples work in the same way as the examples from the previous section.

    Here is a positive floating-point number as an argument:

    my_number = 34.05 abs_value = abs(my_number) print(abs_value) #output #34.05 

    And here is a negative floating-point number as an argument:

    my_number = -43.2 abs_value = abs(my_number) print(abs_value) #output #43.2 

    How to Use the abs() Function with a Complex Number Argument

    Complex numbers work differently from integers and floats.

    When a complex number is passed as an argument to the abs() function, the return value is the magnitude of that number.

    The magnitude of a complex number, such as a+bj , is the number’s distance between the origin (0,0) and the point (a,b) in the complex plane. And the magnitude of a complex number is calculated with the help of the Pythagorean theorem, $\sqrt$

    So, let’s take the complex number 3 + 4j for example. You would need to calculate the square root of the squares of the numbers from the real part ( 3 ) and the imaginary part 4 : $\sqrt$ = 5

    In Python, this is how you would use a complex number with the abs() function:

    my_number = 3 + 4j abs_value = abs(my_number) print(abs_value) #output #5.0 

    Conclusion

    And there you have it – you now know the basics of how the abs() Python function works!

    I hope you found this article helpful.

    To learn more about the Python programming language, check out freeCodeCamp’s Scientific Computing with Python Certification.

    You’ll start from the basics and learn in an interactive and beginner-friendly way. You’ll also build five projects at the end to put into practice and help reinforce what you’ve learned.

    Thank you so much for reading and happy coding 🙂

    Источник

    Функция abs() в Python: синтаксис и примеры использования

    Функция abs() в Python: синтаксис и примеры использования

    Функция abs() в Python является встроенной функцией, которая возвращает абсолютное значение числа.

    Абсолютное значение числа — это его значение без учета знака, то есть расстояние числа от нуля на числовой прямой. В данной статье мы рассмотрим принцип работы функции abs() , ее синтаксис и приведем несколько примеров использования.

    Синтаксис

    Синтаксис функции abs() достаточно прост:

    • x — числовой аргумент (целое число, дробное число или комплексное число), для которого вы хотите получить абсолютное значение.

    Возвращаемые значения функции abs()

    Функция abs() возвращает абсолютное значение аргумента x . Если аргумент является комплексным числом, функция возвращает его модуль (комплексная норма).

    Примеры использования функции abs()

    1. Абсолютное значение целого числа:

    integer = -5 absolute_value = abs(integer) print(f"Абсолютное значение числа равно ") #Абсолютное значение числа -5 равно 5

    2. Абсолютное значение дробного числа:

    float_number = -3.7 absolute_value = abs(float_number) print(f"Абсолютное значение числа равно ") #Абсолютное значение числа -3.7 равно 3.7

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

    complex_number = 3 + 4j absolute_value = abs(complex_number) print(f"Модуль комплексного числа равен ") #Модуль комплексного числа (3+4j) равен 5.0

    Функция abs() может быть полезна при решении различных задач, связанных с числами и вычислениями. Ниже приведены несколько примеров ее использования.

    4. Вычисление расстояния между двумя точками на числовой прямой:

    point_a = 4 point_b = -7 distance = abs(point_a - point_b) print(f"Расстояние между точками и равно ") #Расстояние между точками 4 и -7 равно 11

    5. Определение минимального расстояния между значениями в списке:

    values = [10, 25, 5, 15, 40, 17] min_distance = float('inf') for i in range(len(values)): for j in range(i+1, len(values)): distance = abs(values[i] - values[j]) if distance < min_distance: min_distance = distance closest_pair = (values[i], values[j]) print(f"Минимальное расстояние между числами ") #Минимальное расстояние 2 между числами (15, 17)

    6. Вычисление суммы абсолютных значений чисел в списке:

    numbers = [-3, 5, -1, 7, -4, 9] absolute_sum = sum(abs(number) for number in numbers) print(f"Сумма абсолютных значений чисел в списке равна ") #Сумма абсолютных значений чисел в списке равна 29

    Заключение

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

    Источник

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