Python | fmod()函数

fmod() 函数是Python中的标准数学库函数之一,用于计算指定参数的模块。

null

语法: 数学fmod(x,y)

参数: x任意有效数字(正数或负数)。 y任何有效数字(正数或负数)。

返回: 在计算给定参数x和y的模后返回一个浮点数值。

示例#1:

# Python3 program to demonstrate fmod() function
import math
# Tuple Declaration
Tup = ( 15 , 22 , - 2 , - 40 )
# List Declaration
Lis = [ - 89 , 38 , - 39 , 16 ]
# modulus of +ve integer number
print (math.fmod( 4 , 5 ))
print (math.fmod( 43.50 , 4.5 ))
# modulus of -ve integer number
print (math.fmod( - 17 , 5 ))
print ( '%.2f' % math.fmod( - 10 , 4.78 ))
# modulus of tuple item
print ( "Modulus of tuple items:" )
print (math.fmod(Tup[ 2 ], 5 ))
print (math.fmod(Tup[ 2 ], - 6 ))
# modulus of list item
print ( "Modulus of list items:" )
print (math.fmod(Lis[ 3 ], 4 ))
print (math.fmod(Lis[ 0 ], - 15 ))


输出:

4.0
3.0
-2.0
-0.44

Modulus of tuple items:
-2.0
-2.0

Modulus of list items:
0.0
-14.0

示例2: ValueError和TypeError

  • 如果x和y参数都为零,则fmod()函数将以 值错误 .
  • 如果y参数(第二个参数)为零,则fmod()函数将以 值错误 .
  • 如果x值或y值不是数字,则fmod()函数将返回 打字错误 .

# Python3 program to demonstrate
# errors in fmod() function
import math
# will give ValueError
print (math.fmod( 0 , 0 ))
print (math.fmod( 2 , 0 ))
# it will give TypeError
print (math.fmod( '2' , 3 ))


输出:

ValueError: math domain error
ValueError: math domain error
TypeError: a float is required
© 版权声明
THE END
喜欢就支持一下吧
点赞9 分享