Python abs()函数的绝对值教程和例子

Python提供了 abs() 函数以计算并返回给定数字的绝对值。为了使计算更容易,数学中使用了绝对值。给定的值可以是多种表示形式的不同类型,如浮点、复数、负数、十六进制等。

null

abs()函数语法

abs()函数的语法非常简单,只接受一个参数来计算它的绝对值。

abs(NUMBER)
  • `abs`是返回给定数字绝对值的函数名。
  • `NUMBER`是我们要计算其绝对值的数字。数字可以是浮点数、负数、复数、十六进制、二进制等。

整数的绝对值

我们将从一个简单的例子开始,我们将计算一个整数的绝对值。

abs(5)//Equal to the 5abs(55)//Equal to the 55abs(550)//Equal to the 550abs(0)//Equal to the 0abs(-5)//Equal to the 5abs(-55)//Equal to the 55abs(-550)//Equal to the 550abs(-999)//Equal to the 999
Absolute Value For A Integer
整数的绝对值

从这些例子中我们可以看出,一个整数将被转换成一个整数作为一个绝对值。正整数将转换为与绝对值相同的值。负整数将转换为与整数相同的正数。 55 绝对值为 55 -55 绝对值为 55 我也是。

浮点的绝对值

abs()函数或绝对值最常用的场景之一是浮点数。

abs(0.5)//Equal to the 0.5abs(1.5)//Equal to the 1.5abs(-1.5)//Equal to the 1.5abs(-0.5)//Equal to the 0.5abs(-100.9)//Equal to the 100.9abs(100.9)//Equal to the 100.9
Absolute Value For A Floating Point
浮点的绝对值

复数的绝对值

abs()函数也可以用于复数。我们将在这些例子中提供不同的复数。

abs(5-4j)//Equal to the 6.4031242374328485abs(30-4j)//Equal to the 30.265491900843113abs(300-4j)//Equal to the 300.0266654815868abs(31-4j)//Equal to the 31.25699921617557abs(1-4j)//Equal to the 4.123105625617661abs(2-4j)//Equal to the 4.47213595499958abs(10-40j)//Equal to the 41.23105625617661
Absolute Value For A Complex Number
复数的绝对值

二进制数的绝对值

二进制数可以用于绝对计算,如下所示。

abs(0b1101101)//Equal to the 109abs(0b110110)//Equal to the 54abs(0b11011)//Equal to the 27abs(0b1101)//Equal to the 13abs(0b110)//Equal to the 6abs(0b11)//Equal to the 3abs(0b1)//Equal to the 1
Absolute Value For A Binary Number
二进制数的绝对值

八进制的绝对值

我们可以计算八进制数的绝对值,如下所示。

abs(0o11011010)//Equal to the 2363912abs(0o11011014)//Equal to the 2363916abs(0o1102014)//Equal to the 295948abs(0o1152014)//Equal to the 316428abs(0o152014)//Equal to the 54284abs(0o152614)//Equal to the 54668abs(0o15267)//Equal to the 6839
Absolute Value For Octal
八进制的绝对值

十六进制的绝对值

我们也可以使用abs()函数来计算十六进制值。

abs(0x23ADF042)//Equal to the598601794abs(0x23ADF04)//Equal to the37412612abs(0x23ADF0)//Equal to the2338288abs(0x23ADF)//Equal to the146143abs(0x23AD)//Equal to the9133abs(0x23A)//Equal to the570abs(0x23)//Equal to the35abs(0x2)//Equal to the2
Absolute Value For Hexadecimal
十六进制的绝对值

列表项的绝对值

Python是一种实用的语言,在这里我们可以计算给定列表项的绝对值。我们将使用 map() 函数,并为abs()函数提供列表。

numbers=[10,15,20,-10,-15-20,0.5,-0.5]numbers_obsolute = map(abs,numbers)print(list(numbers_obsolute))[10, 15, 20, 10, 35, 0.5, 0.5]
Absolute Value For The List Items
列表项的绝对值
© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享