Python Absolute Value with examples

The abs() function in Python returns a number’s absolute value. The gap between an integer and zero is its absolute value. Any negative number becomes positive, whereas positive ones remain unchanged. For instance, abs(-9) returns 9, whereas abs(2) returns 2.

On the number line, an absolute value is the distance between a number and 0. These numbers come in handy in a variety of math problems. Absolute values, for example, are utilized in distance calculations.

This is where the built-in function abs() comes in. The absolute value of a given number can be calculated using the abs() function. This article will look at using Python’s abs() method. We’ll also look at a few examples to see how their function work.

An Explanation of Absolute Value in Python

An absolute value in mathematics refers to how distant a number is from zero on the number line. The absolute value of a number is always positive, regardless of whether it is positive or negative. The absolute value of 5 is 5, for example. -5 has the same absolute value as 5. The latter is because 5 and -5 are five places apart on the number line. -5 is five places away from zero, and five is five spaces away.

Absolute value is a fundamental idea in mathematics and physics, with numerous applications in both domains. In data analysis, absolute values are frequently utilized.

Absolute Value in Python

The abs() function in Python calculates a number’s absolute value. The abs() function only accepts one argument: the number whose absolute value you want to find. The abs() method has the following syntax:

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>abs(value)</pre>
</div>

Depending on the value you send to the abs() method, it returns a floating-point number or an integer:

-78 returns 78, whereas -43.6 returns 43.6.

The floating-point value is 2.2, shown by the period in the number. abs() does not require numerical conversion because it supports both integers and floating-point values.

Parameters: (value)

The value to pass to abs() to obtain the absolute value. An integer, float, or complex number is used.

Return Value:

  • The absolute value of the provided number is returned.
  • The return value will be an integer if the input is an integer.
  • The return value will be afloat if the input is afloat.
  • The magnitude of the input will be the return value if the input is a complex number.

abs() can work with negative and positive numbers (including floating numbers and integers). The abs() function, on the other hand, will return the same result as the value parsed by the function. It is a positive number because 0 is not a negative number. Let’s look at how the abs() method works.

Example of the Python abs() method

Assume the local police department employs you. They want you to create an app that determines whether or not cars on a specific road are due for a speeding ticket. Drivers should travel at about the same pace as the average motorist on this road.

Because of a series of accidents on the road, the police department does not want anyone to violate this limit. Many of the collisions were caused by extreme speed differences among drivers. It’s dangerous to drive more than 10 miles per hour (ca. 16 km/h) faster or slower than the typical driver. A ticket should be issued to drivers who exceed this restriction.

Considering the Speed

We’ll create a program to determine whether or not a driver should be ticketed based on their speed:

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>average_speed = 120
current_speed = 85

speed_difference = average_speed - current_speed

final_absolute_value = abs(speed_difference)

print(final_absolute_value )

# Our code returns the following: 35.</pre>
</div>

We declared a Python variable on the first line of code. The average speed of cars on the route is stored in this variable, which was 120 mph (about 194 km/h). Then we declared a variable to hold a specific driver’s current speed—in this case, 85 mph (about 137 km/h).

We estimated the difference between the present speed of the specified drivers and the average speed of cars on the road on the next line. Then we used the abs() method to retrieve the absolute value of this value.

In technical terms, the gap between the driver’s speed and the average speed is -35 mph (ca. 56 km/h). But all we wanted to know was the difference in speed between the individual driver and the average speed of automobiles on the route. Our application returned 35 after using abs() to convert our value to an absolute value.

Message Displaying

If a driver is due a ticket, we want our program to display a notice. We may accomplish this by adding a Python if statement to the end of our previous program.”

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>print("Difference in speeds: " + absolute_value)

if absolute_value > 25:
	print(" racing driver is exceeding the stipulated speed limit. Issue a ticket to them.")
else:
	print("This racing driver is within the stipulated  speed limits.")</pre>
</div>

The driver’s speed difference is first printed on the console. Then we use an if statement to see if the driver is going over the speed limit. A different Python print statement is executed depending on whether the motorist exceeds or follows the speed restriction.

Absolute Distance Calculations in Python

In distance computations, absolute values are frequently utilized. Let’s pretend we’re trying to get 20 miles (32 kilometers) away from our house. We travel 31 miles by mistake.

We would get a negative figure if we wanted to know how many miles we had left till we arrived at our destination. We could use abs() to turn that negative integer into a positive one. The following is the Python code for an example that uses the abs() function:

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>miles_from_home = 30
travelled = 41

miles_left = miles_from_home - travelled

print(abs(miles_left))


# Our code produces the following: 11.</pre>
</div>

Our program would have returned -11 if we hadn’t specified abs() because the difference between 30 and 41 is -11. Our software, however, produced an absolute result because we used abs().

List Absolute Value in Python

A list is a variable that contains information from many data types. This section will learn about the absolute value of a list in Python. We will find the absolute value of each item in the list using the abs() function in Python.

Make sure that all of the entries in the list are either integers, floats, or complex numbers before using this technique. Python’s abs() method does not operate with other data types. We’ve built a list of integer, float, and complex numbers in our example. The output will be the list’s absolute value in Python.

Using the abs () technique, we built a list with numbers (integers, floats, and complexes) with this code and converted these values inside the list using the abs() technique. We used a for loop to pass the list through, storing the value in an empty list and then printing the list as a result.

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>list_with_no_abs = [3, 5.2, -9, -1.91j]
print('There are no absolute values in this list. : ', list_with_no_abs)

list_having_abs = []
for val in list_with_no_abs:
    list_having_abs.append(abs(val))

print("Absolute value listing ",str(list_having_abs))</pre>
</div>

Values within the list are transformed into absolute values in this output. Absolute merely records the value and disregards the sign. There is no negative value in the final result.

Absolute Value Function in Python

The absolute value function in Python is covered in this section. The abs() method in Python is used to calculate the absolute value of an integer.

The absolute function ignores the number’s sign and returns merely the number. In other words, if a negative value is supplied, the positive value is returned. The abs () method in Python can provide integer, float, or complex values to Python’s abs() method. In our example, we’ve written a function that will ask the user for a number and then return the number’s absolute value.

We’ve constructed a function that accepts a value from the user in this code. Inside the python exception handling blocks, the program is placed. The function returns the number’s absolute value. This function has also been called numerous times to make things clearer.

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>def codeFindAbsolute(val):
    try:
        return print("The final Result:",abs(val))
    except for ValueError:
        return print("Only integers, floats, and complex numbers are permitted. ")

#a complex number
codeFindAbsolute(-2.7j)
codeFindAbsolute(2.71j)

#The integer number
codeFindAbsolute(6)
codeFindAbsolute(-6)

#The float number
codeFindAbsolute(7.4)
codeFindAbsolute(-7.4)

# The string
codeFindAbsolute('Manchester United')
</pre>
</div>

We’ve included the results for each datatype in this output (integer, float, and complex). When we passed the python string value into the function, the software threw an error.

Absolute Value of a Complex Number in Python

A complex number comprises two numbers: a real and an imagined one. We’ll learn how to find the absolute value of complex integers in Python in this section. You might be wondering what the complex number’s imaginary number is. In mathematics, imaginary numbers are those that have yet to be solved. And these numbers are expressed by prefixing the real number with j or J. (s). The value of PI () = 3.1428514 is an example of a complex number, and the list goes on. So, to make things easier, we can write it like this:

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>3.14+0j</pre>
</div>

We’ll use Python to convert a complicated number to an absolute value in this example. In this code, we’ve requested user input in the form of complex numbers, which are then transformed to absolute values using the built-in abs() method in Python.

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>num = complex(input('Enter Complex Number: '))
print(type(num))
print("Result:",abs(num))</pre>
</div>

The program is run twice in this output. The first time we entered 2+3j, the result was positive, and the second time we entered -2+3j, the result was negative. This number is similar to the preceding one, except it has a negative sign instead of a positive one, and the absolute value is the same. The minus symbol is overlooked.

Absolute Value Math in Python

The Python Math module has several techniques for solving mathematical problems in Python. We’ll learn about absolute value in Python using the math module in this section. The absolute value of the provided number can be calculated using the fabs() method in the Python math module. The first step involves importing the built-in math module in Python.

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>import math

print("result:",math.fabs(-21))</pre>
</div>

The user-supplied -21 in this output and the math.fabs() module in Python returned 21.0.

Python Absolute Value Without ABS

We will learn about absolute value in Python without using the abs function in this part. There are several alternatives to using Python’s built-in abs() method to get absolute values. These additional methods are known as hacks, and they do not ensure that they will work in all circumstances.

You can use an if-else ladder to print only the positive value for a number, which is also a task that complex numbers can perform, although it may not work with complex numbers. Another option is to raise the number to the power of two and then do a 0.5 raised to the power of the result. The negative sign is removed in the first portion, and the number is restored to its original value in the second.

We’ve developed a function called manual abs() in this code. This function is known for taking an integer as an argument and returning the number’s absolute value. It calculates the 2 raise the power of number result first. Then the 0.5 raise the power result.

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>def manual_abs(num):
    return (num**2)**(0.5)

print(manual_abs(-5))</pre>
</div>

-5 is entered as a parameter in this output, and the result 5.0 is created as an output.

Absolute Value DataFrame in Python

The absolute value data frame in Python is covered in this section. We’ve developed a dataset for the Traffic Incident report as an example. We will only execute operations on the Latitude and Longitude columns because the absolute value can only be calculated using numbers (integer, float, complex). In other words, the Python Absolute Value of Column will be covered.

Use of Pandas

We may calculate the absolute value of a column using Python Pandas’ DataFrame.abs method. This function is only used on columns that have numeric values. The dataset ‘traffic incident report.csv’ was taken from the Kaggle website and utilized in this source code. This dataset has been adjusted to meet our needs.

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre># import module
import pandas as pd

# read csv file
df = pd.read_csv('code_traffic_incident_report.csv')

# absolute value of Latitude column
lat = df.Latitude.abs()

# absolute value of Longitute column
long = df.Longitude.abs()

# adding column to exsiting dataframe
df['abs_lat'] = lat
df['abs_long'] = long

# display
print(df)</pre>
</div>

We used the jupyter notebook to implement the program in this output. If you don’t have a Jupyter notebook, you can use print(df) to display the data. The absolute value of the latitude and longitude column was determined here, and then we added the column to the existing dataframe.

Example: Integer and Float Numbers in Code

Check out this code to get the absolute value of an integer or float number:

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre># abs() with an integer and afloat

code_int_num = -38

code_float_num = -13.50

print(" An integer number's absolute value is :", abs(code_int_num))
print("A float number's absolute value is  :", abs(code_float_num))</pre>
</div>

Example: Complex Number

To calculate the absolute value of a complicated number.

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre># abs() is being used to test a complicated integer.

complex_num = (8+10j)

print("The complex number's magnitude is  :", abs(complex_num))</pre>
</div>

Example: Distance computation with absolute values in Python

The link between speed, distance traveled, and time taken is seen in this equation:

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>code_distance  = code_speed * code_time
code_time = code_distance / code_speed
code_speed = code_distance / code_time</pre>
</div>

Distance divided by time equals speed. Because we know that speed, time, and distance can never be negative, we’ll use abs() to calculate the precise time, distance, and speed.

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre># Program for calculating speed, distance and time in Python

# Speed calculation function
def code_cal_speed(code_dist, code_time):
	print(" The Distance in (km) is :", code_dist)
	print(" The Time(hr) is :", code_time)
	return code_dist / code_time

# Distance traveled calculation function
def code_cal_dis(code_speed, code_time):
	print(" The Time(hr) is :", code_time)
	print(" The Speed(km / hr)  is:", code_speed)
	return code_speed * code_time

# Calculate the amount of time it takes
def code_cal_time(code_dist, code_speed):
	print(" The Distance(km) is :", code_dist)
	print(" The Speed(km / hr) is :", code_speed)
	return code_speed * code_dist

# This is the primary code
# that calls the function code_cal_speed()
print(" The resultant speed calculated (km / hr) is :",
	code_cal_speed(abs(85.9), abs(2.0)))
print("")

# Calling the function code_cal_dis()
print(" The  resultant Distance calculated (km)  is:",
	cal_dis(abs(32.9), abs(2.5)))
print("")

# Calling function cal_time()
print(" The resultant Time calculated (hr) :",
	code_cal_time(abs(96.0), abs(4.5)))</pre>
</div>

Conclusion

Using Python’s abs () function, a floating-point number or an integer can be converted to an absolute value using Python’s abs() function. It is particularly handy when determining the difference between two values. With the help of the examples, we looked at how to utilize abs() in Python in this article.

Python abs() is a built-in function with the Python standard library. The absolute value of the provided number is returned. A number’s absolute value is its value without regard to its sign.

Integers, floating-point numbers, and complex numbers are all possible. If the specified number is complex, the magnitude is returned. The abs() method only accepts one input, the absolute value.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *