Movatterモバイル変換


[0]ホーム

URL:


— FREE Email Series —

🐍 Python Tricks 💌

Python Tricks Dictionary Merge

🔒 No spam. Unsubscribe any time.

Browse TopicsGuided Learning Paths
Basics Intermediate Advanced
apibest-practicescareercommunitydatabasesdata-sciencedata-structuresdata-vizdevopsdjangodockereditorsflaskfront-endgamedevguimachine-learningnumpyprojectspythontestingtoolsweb-devweb-scraping

Table of Contents

How to Find the Absolute Value in Python

How to Find an Absolute Value in Python

byBartosz Zaczyńskibasicspython

Table of Contents

Remove ads

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 theabsolute value function from scratch
  • Use thebuilt-inabs() function in Python
  • Calculate the absolute values ofnumbers
  • Callabs() onNumPy arrays andpandas series
  • Customize thebehavior ofabs() 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.

Get Your Code:Click here to download the free sample code that you’ll use to find absolute values in Python.

Defining the Absolute Value

The absolute value lets you determine thesize ormagnitude of an object, such as a number or avector, 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.

Note: When you take the absolute value of a number, you lose information about its sign or, more generally, its direction.

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 phrasebelow 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 apiecewise 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 thedistance from the origin, which is zero on anumber 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 thedirection and themagnitude of a physical quantity, but in more than one dimension. For example, you can express thevelocity 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’sspeed measured in meters per unit of time.

Note: There are two ways to look at a vector. Abound vector is an ordered pair of fixed points in space, whereas afree vector only tells you about the displacement of the coordinates from point A to point B without revealing their absolute locations. Consider the following code snippet as an example:

Python
>>>A=[1,2,3]>>>B=[3,2,1]>>>bound_vector=[A,B]>>>bound_vector[[1, 2, 3], [3, 2, 1]]>>>free_vector=[b-afora,binzip(A,B)]>>>free_vector[2, 0, -2]

A bound vector wraps both points, providing quite a bit of information. In contrast, a free vector only represents the shift from A to B. You can calculate a free vector by subtracting the initial point, A, from the terminal one, B. One way to do so is by iterating over the consecutive pairs of coordinates with alist comprehension.

A free vector is essentially a bound vector translated to the origin of the coordinate system, so it begins at zero.

Thelength of a vector, also known as its magnitude, is the distance between its initial and terminal points, 𝐴 and 𝐵, which you can calculate using theEuclidean 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:

Python
defabsolute_value(x):ifx>=0:returnxelse:return-x

You use aconditional statement to check whether the given number denoted with the letterx 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 aconditional expression that comfortably fits on a single line:

Python
defabsolute_value(x):returnxifx>=0else-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.

Note: Alternatively, you can write this even more concisely by relying on Python’s built-inmax() function, which returns the largest argument:

Python
defabsolute_value(x):returnmax(x,-x)

If the number 𝑥 is negative, then this function will return its positive value. Otherwise, it’ll return 𝑥 itself.

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

Python
frommathimportsqrtdefabsolute_value(x):returnsqrt(pow(x,2))

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

Python
defabsolute_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:

Python
>>>defabsolute_value(x):...return(x**2)**0.5>>>absolute_value(-12)12.0>>>type(12.0)<class 'float'>

You always end up with afloating-point number, even if you started with aninteger. 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:

Python
defabsolute_value(x):returnfloat(str(x).lstrip("-"))

You convert the function’s argument,x, to aPython string using the built-instr() 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 withfloat(). 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-inabs() function that comes with Python. You’ll find out why in the next section.

Using the Built-inabs() 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 theabs() function that’s built into the language. That’s becauseabs() is compiled to blazing-fastmachine code, while your pure-Python code isn’t.

You should always preferabs() 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

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

Python
>>>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 Pythonfloat. But these two data types aren’t the only ones that you can callabs() on. The third numeric type thatabs() knows how to handle is Python’scomplex data type, which represents complex numbers.

Complex Numbers

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

Python
>>>z=complex(3,2)

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:

Python
>>>z.real3.0>>>z.imag2.0

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

Python
>>>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 byabs(). Note that the absolute value of a complex number is more commonly referred to as themagnitude,modulus, orradius 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 theabs() function.

Fractions and Decimals

Theabs() function in Python accepts all numeric data types available, including the lesser-knownfractions anddecimals. For instance, you can get the absolute value of one-third or minus three-quarters defined asFraction instances:

Python
>>>fromfractionsimportFraction>>>abs(Fraction("1/3"))Fraction(1, 3)>>>abs(Fraction("-3/4"))Fraction(3, 4)

In both cases, you get anotherFraction 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 useDecimal objects to help mitigate thefloating-point representation error. Luckily, you can take the absolute value of these objects:

Python
>>>fromdecimalimportDecimal>>>abs(Decimal("0.3333333333333333"))Decimal('0.3333333333333333')>>>abs(Decimal("-0.75"))Decimal('0.75')

Again, theabs() 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 thatabs() 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.

Callingabs() 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 callingabs() on a Python list with those numbers, you get an error:

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

That’s becauseabs() doesn’t know how to process a list of numbers. To work around this, you could use a list comprehension or callPython’smap() function, like so:

Python
>>>[abs(x)forxintemperature_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 ofabs() 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 isNumPy. Its 𝑛-dimensional array data structure,ndarray, is the cornerstone ofnumerical computing in Python, so many other libraries use it as a foundation.

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

Python
>>>importnumpyasnp>>>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 callingabs() 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 theabs() 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:

Python
>>>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 andslicing, 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 indata analysis thanks to itsSeries andDataFrame objects. A series is a sequence of observations or a column, whereas aDataFrame is like a table or a collection of columns. You can callabs() on both of them.

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

Python
>>>lowest_temperatures={..."Reykjav\xedk":[-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 pandasDataFrame object so that you can draw some interesting insights going forward:

Python
>>>importcalendar>>>importpandasaspd>>>df=pd.DataFrame(lowest_temperatures,index=calendar.month_abbr[1:])>>>df     Reykjavík  Rovaniemi  ValettaJan         -3        -16        9Feb         -2        -14        9Mar         -2        -10       10Apr          1         -3       12May          4          3       15Jun          7          8       19Jul          9         12       21Aug          8          9       22Sep          6          5       20Oct          2         -1       17Nov         -1         -6       14Dec         -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 thecalendar module. Each column in the DataFrame has a sequence of temperatures from the original dictionary, represented as aSeries object:

Python
>>>df["Rovaniemi"]Jan   -16Feb   -14Mar   -10Apr    -3May     3Jun     8Jul    12Aug     9Sep     5Oct    -1Nov    -6Dec   -11Name: 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 singleSeries 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 itsDataFrame andSeries objects. Specifically, you can callabs() to calculate more than one absolute value in one go:

Python
>>>abs(df)     Reykjavík  Rovaniemi  ValettaJan          3         16        9Feb          2         14        9Mar          2         10       10Apr          1          3       12May          4          3       15Jun          7          8       19Jul          9         12       21Aug          8          9       22Sep          6          5       20Oct          2          1       17Nov          1          6       14Dec          2         11       11>>>abs(df["Rovaniemi"])Jan    16Feb    14Mar    10Apr     3May     3Jun     8Jul    12Aug     9Sep     5Oct     1Nov     6Dec    11Name: Rovaniemi, dtype: int64

Callingabs() on the entire DataFrame applies the function to each element in every column. You can also callabs() on the individual column.

How did NumPy and pandas change the behavior of Python’s built-inabs() 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 ofabs(), 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 callabs() on an integer, it’ll use a custom code snippet that resembles your piecewise function. However, that function will be implemented in theC programming language for efficiency. If you pass a floating-point number, then Python will delegate that call to C’sfabs() function. In the case of a complex number, it’ll call thehypot() 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 theabs() function because its default behavior is unknown. However, you can optionally customize the behavior ofabs() against the instances of your class by implementing the special.__abs__() method using pure Python. There’s a finite set of predefinedspecial methods in Python that let you override how certain functions and operators should work.

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

Python
>>>importmath>>>classVector:...def__init__(self,*coordinates):...self.coordinates=coordinates......def__abs__(self):...origin=[0]*len(self.coordinates)...returnmath.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 theEuclidean norm definition that you learned at the beginning of this tutorial.

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

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

Notice how callingabs() on yourVector 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 yourVector class represents a free vector rather than a bound one, you can simplify your code by calculating the multidimensionalhypotenuse using Python’smath.hypot() function:

Python
>>>importmath>>>classVector:...def__init__(self,*coordinates):...self.coordinates=coordinates......def__abs__(self):...returnmath.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 thathypot() is avariadic 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-inabs() 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 versatileabs() 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 useabs() on instances of custom classes and third-party library objects.

In this tutorial, you learned how to:

  • Implement theabsolute value function from scratch
  • Use thebuilt-inabs() function in Python
  • Calculate the absolute values ofnumbers
  • Callabs() onNumPy arrays andpandas series
  • Customize thebehavior ofabs() on objects

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

Get Your Code:Click here to download the free sample code that you’ll use to find absolute values in Python.

🐍 Python Tricks 💌

Get a short & sweetPython Trick delivered to your inbox every couple of days. No spam ever. Unsubscribe any time. Curated by the Real Python team.

Python Tricks Dictionary Merge

AboutBartosz Zaczyński

Bartosz is a bootcamp instructor, author, and polyglot programmer in love with Python. He helps his students get into software engineering by sharing over a decade of commercial experience in the IT industry.

» More about Bartosz

Each tutorial at Real Python is created by a team of developers so that it meets our high quality standards. The team members who worked on this tutorial are:

MasterReal-World Python Skills With Unlimited Access to Real Python

Locked learning resources

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

Level Up Your Python Skills »

MasterReal-World Python Skills
With Unlimited Access to Real Python

Locked learning resources

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

Level Up Your Python Skills »

What Do You Think?

Rate this article:

What’s your #1 takeaway or favorite thing you learned? How are you going to put your newfound skills to use? Leave a comment below and let us know.

Commenting Tips: The most useful comments are those written with the goal of learning from or helping out other students.Get tips for asking good questions andget answers to common questions in our support portal.


Looking for a real-time conversation? Visit theReal Python Community Chat or join the next“Office Hours” Live Q&A Session. Happy Pythoning!

Keep Learning

Related Topics:basicspython

Related Tutorials:

Keep reading Real Python by creating a free account or signing in:

Already have an account?Sign-In

Almost there! Complete this form and click the button below to gain instant access:

How to Find the Absolute Value in Python

How to Find an Absolute Value in Python (Sample Code)

🔒 No spam. We take your privacy seriously.


[8]ページ先頭

©2009-2025 Movatter.jp