Python program to find difference between two given numbers

Python program to find difference between two given numbers

This tutorial guides you different ways to find difference between two given numbers using Python programing without knowing which number is biggest between two given numbers.

Python program to find difference between two given numbers

The following are the different methods or ways you can follow to find the difference between two given numbers in Python.

Python program to find difference between two given numbers

Β 

Method 1: abs() built-in function

The built-in function abs() returns the absolute value of a number. Note, the argument can be an integer or floating point number or an object implementing __abs__(). And if the argument is complex number, then its magnitude is returned.

Also check the either x > y or x < y, you will get the difference between two given numbers the same value 1 i.e., this function will always return the net difference between two positive numbers.

For example,

>>> x=5
>>> y=4
>>> abs(4-5)
1
>>> abs(5-4)
1
>>> x=4
>>> y=5
>>> abs(4-5)
1
>>> abs(5-4)
1

Method 2: math.fabs(x)

We can also use mathematical functions as shown below. The function math.fabs(x) return the absolute value of x.

For example,

>>> import math
>>> x=4
>>> y=5
>>> math.fabs(x-y)
1.0

>>> x=5
>>> y=4
>>> math.fabs(x-y)
1.0

Method 3: math.dist(x,y)

This mathematical function returns the euclidean distance between two points x and y. Note, the two points must have the same dimension.

For example, to find the difference between two given positive numbers using math.dist().

>>> import math
>>> x=[4]
>>> y=[5]
>>> math.dist(x,y)
1.0

>>> x=[5]
>>> y=[4]
>>> math.dist(x,y)
1.0

Method 4: max() and min() built-in functions

You can also find the difference using max() and min() Python built-in functions.

For example,

>>> max(x-y, y-x)
1

>>> -min(x-y, y-x)
1

Also, we can use both max() and min() together in the following way.

>>> max(x,y)-min(x,y)
1

That’s it. Hope you had learnt numerous ways to find the difference between two given positive numbers in Python programming languauge.

Hope it helped πŸ™‚

You’ll also like:

References

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments