python中math modf例子_Python math modf()用法及代码示例

modf()函数是Python中的内置函数,它返回two-item元组中数字的小数和整数部分。两个部分的符号与数字相同。整数部分以浮点数形式返回。

用法:

modf(number)

参数:

There is only one mandatory parameter which is the number.

返回值:

此方法返回two-item元组中数字的小数和整数部分。两个部分的符号与数字相同。整数部分以浮点数形式返回。

异常:

TypeError: If anything other then a float number is passed, it returns a type error.

下面是modf()方法的Python3实现:

代码#1

# Python3 program to demonstrate the function modf()

# This will import math module

import math

# modf() function used with a positive number

print("math.modf(100.12):", math.modf(100.12))

# modf() function used with a negative number

print("math.modf(-100.72):", math.modf(-100.72))

print("math.modf(2):", math.modf(2))

输出:

math.modf(100.12): (0.12000000000000455, 100.0)

math.modf(-100.72): (-0.7199999999999989, -100.0)

math.modf(2): (0.0, 2.0)

代码2:TypeError

# Python3 program to demonstrate the

# error in function modf()

# This will import math module

import math

# modf() function used with a positive number

print("math.modf(100.12):", math.modf("100.12"))

输出:

Traceback (most recent call last):

File "/home/fa6d7643de17bafe9a0e0693458e4bdb.py", line 9, in

print("math.modf(100.12):", math.modf("100.12"))

TypeError:a float is required

代码#3:

# Python3 program to demonstrate the

# error in function modf()

# This will import math module

from math import modf

lst = [3.12, -5.14, 13.25, -5.21]

tpl = (33.12, -15.25, 3.15, -31.2)

# modf() function on elements of list

print("modf() on First list element:", modf(lst[0]))

print("modf() on third list element:", modf(lst[2]))

# modf() function on elements of tuple

print("modf() on Second tuple element:", modf(tpl[1]))

print("modf() on Fourth tuple element:", modf(tpl[3]))

输出:

modf() on First list element: (0.1200000000000001, 3.0)

modf() on third list element: (0.25, 13.0)

modf() on Second tuple element: (-0.25, -15.0)

modf() on Fourth tuple element: (-0.1999999999999993, -31.0)

实际应用:

给定两个浮点数,将小数部分相乘并返回答案。

代码4:

# Python3 program to demonstrate the

# application of function modf()

# This will import math module

import math

# modf() function to multiply fractional part

a = math.modf(11.2)

b = math.modf(12.3)

# Multiply the fractional part as is stored

# in 0th index of both the tuple

print(a[0]*b[0])

输出:

0.05999999999999993

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值