Python中的fabs方法用于返回一个数的绝对值。

它可以通过导入math模块来使用。

Python中的math模块可用于执行不同的基本数学运算,如加法、减法、除法和乘法。

它还可用于执行涉及指数、对数和三角函数的计算。

语法

在Python中使用fabs的语法如下-

math.fabs(x)  

现在让我们看一些程序,以更好地理解它。

程序1:

在第一个程序中,我们将讨论fabs方法的基础知识。

#working of fabs()  
import math  
# initializing the variables a, b, and c  
a = -20.3  
b = -30.66  
c = 19.13  
#printing the values  
print ("The fabs of a is: ", math.fabs(a))  
print ("The fabs of b is: ", math.fabs(b))  
print ("The fabs of c is: ", math.fabs(c))  

输出:

The fabs of a is:  20.3
The fabs of b is:  30.66
The fabs of c is:  19.13

解释:

让我们来看看这个程序的解释-

  1. 由于我们要使用fabs(),我们导入了math模块。
  2. 然后,我们使用正数和负数值初始化了变量a、b和c。
  3. 在接下来的步骤中,我们将这些值传递给fabs()并打印它们。
  4. 执行程序后,它会显示所期望的输出。

程序2:

在下一个程序中,我们将对这些数字执行一些基本操作,涉及到fabs()的使用。

以下程序演示了相同的内容-

#working of fabs()  
import math  
# initializing the variables a, b, and c  
a = -20.3  
b = -30.66  
c = 19.13  
# calculating the sum  
print ("The sum of a and b is: ", (a + b))  
print ("The sum of b and c is: ", (b + c))  
# printing the values  
d = math.fabs(a)  
e = math.fabs(b)  
f = math.fabs(c)  
#calculating sum after fabs  
print ("The sum of d and e is: ", (d + e))  
print ("The sum of e and f is: ", (e +  f))  

输出:

The sum of a and b is:  -50.96
The sum of b and c is:  -11.530000000000001
The sum of d and e is:  50.96
The sum of e and f is:  49.79

解释:

让我们看看上面程序中做了什么-

  1. 由于我们要使用fabs(),我们导入了math模块。
  2. 然后,我们使用正数和负数值初始化了变量a、b和c。
  3. 接下来,我们打印a + b和b + c的和。
  4. 现在,我们将这三个变量传递给fabs(),并将返回的值存储在变量d、e和f中。
  5. 我们再次计算和,以检查在传入fabs之前和之后使用的值之间的差异。
  6. 执行程序后,它会显示所期望的输出。

程序3:

最后,在最后一个程序中,我们将对这些数字执行更多的数学操作。

#working of fabs()  
import math  
#initialising the variables a, b and c  
a = -20.3  
b = -30.66  
c = 19.13  
#calculating the product  
print ("The product of a and b is: ", (a * b))  
print ("The product of b and c is: ", (b * c))  
#printing the values  
d = math.fabs(a)  
e = math.fabs(b)  
f = math.fabs(c)  
#calculating product after fabs  
print ("The product of d and e is: ", (d * e))  
print ("The product of e and f is: ", (e * f))  

输出:

The product of a and b is:  622.398
The product of b and c is:  -586.5258
The product of d and e is:  622.398
The product of e and f is:  586.5258

解释:

让我们来看看这个程序的解释-

  1. 由于我们要使用fabs(),我们导入了math模块。
  2. 然后,我们使用正数和负数值初始化了变量a、b和c。
  3. 接下来,我们打印a b和b c的乘积。
  4. 现在,我们将这三个变量传递给fabs(),并将返回的值存储在变量d、e和f中。
  5. 我们再次计算乘积,以检查在传入fabs之前和之后使用的值之间的差异。
  6. 执行程序后,它会显示所期望的输出。

结论

在本教程中,我们学习了fabs()以及它们如何在Python程序中使用,以使我们的工作更加容易。

标签: Tkinter教程, Tkinter安装, Tkinter库, Tkinter入门, Tkinter学习, Tkinter入门教程, Tkinter, Tkinter进阶, Tkinter指南, Tkinter学习指南, Tkinter进阶教程, Tkinter编程