lettura simple

The Python abs() Function

In Python, the versatile abs() function serves a dual purpose: it computes the absolute value of numbers and the magnitude (or modulus) of complex numbers.

abs(x)

When you call abs(x), the function behaves differently based on the type of the argument x:

  • When `x` is a real number, abs() returns its absolute value. This is essentially the number's distance from zero, irrespective of its positive or negative sign. For instance, the absolute value of -5.5 is 5.5. Why? Because distance is always positive. Mathematically, this is represented as: $$ |-5.5| = 5.5 $$
  • If `x` is a complex number, abs() provides its magnitude (or modulus). Consider the complex number z=3+4i. Its modulus, representing its distance from the origin on the Gaussian plane, is calculated as: $$ |z| = \sqrt{3^2 + 4^2} $$

In the next two sections, we'll explore in depth, through hands-on examples, the results of the abs function when applied to real and complex numbers.

Absolute Value

To illustrate, let's compute the absolute value of -5:

abs(-5)

This returns 5, indicating that -5 is five units away from zero on the number line.

5

Similarly, for 5.5:

abs(5.5)

The result, unsurprisingly, is 5.5.

5.5

Modulus of a complex number

Complex numbers, denoted as z=a+bi, have both a real part "a" and an imaginary part "b". The `abs` function can also compute the modulus of these numbers.

For instance, defining the complex number 3+4i.

z=complex(3,4)

This complex number corresponds to the point (3,4) on the Gaussian plane.

To find its modulus:

abs(z)

This returns 5.0, representing the distance of point (3,4) from the origin on the Gaussian plane.

5.0

To further understand, the magnitude (or modulus) of a complex number is derived from the formula:

$$ |z| = \sqrt{a^2 + b^2} $$

Using our example where the real part is 3 and the imaginary part is 4.

$$ |z| = \sqrt{3^2 + 4^2} $$

$$ |z| = \sqrt{9 + 16} $$

$$ |z| = \sqrt{25} $$

$$ |z| = 5 $$

Hence, abs(z) rightfully returns 5.0.




Report a mistake or post a question




FacebookTwitterLinkedinLinkedin