Python math.modf() Function
In numerical computation, sometimes we need toseparate the integer part and the fractional part of a number. For example, extracting 3 and 0.14 from 3.14.
math.modf() is a function designed specifically for this operation; it returns a tuple containing the number'sfractional partandinteger part。
Word meaning: modf is an abbreviation of "modular fractional", meaning "fractional part".
Basic syntax and parameters
Syntax format
import math
math.modf(x)
Parameter Description
- Parameters:
x- A numeric value (integer or floating-point)
Return Value
- Returns a tuple
(fractional, integer) fractional: the fractional part, with the same sign as xinteger: the integer part (truncated toward zero)
Example
Example 1: basic usage
Example
import
math
result
=
math
.
modf
(
3.14159
)
(
"math.modf(3.14159) ="
,
result
)
fractional
,
integer
=
math
.
modf
(
3.14159
)
(
f
"Fractional part: {fractional}, integer part: {integer}"
)
Result:
math.modf(3.14159) = (0.14158999999999988, 3.0)
小数部分: 0.14158999999999988, 整数部分: 3.0
Example 2: handling negative numbers
Example
import
math
(
"math.modf(-3.14) ="
,
math
.
modf
(
3.14
)
)
(
"math.modf(-0.5) ="
,
math
.
modf
(
0.5
)
)
fractional
,
integer
=
math
.
modf
(
3.14
)
(
f
"Fractional part: {fractional}, integer part: {integer}"
)
Result:
math.modf(-3.14) = (-0.14000000000000012, -3.0)
math.modf(-0.5) = (-0.5, -0.0)
小数部分: -0.14, 整数部分: -3.0
Example 3: handling integers
Example
import
math
(
"math.modf(5) ="
,
math
.
modf
(
5
)
)
(
"math.modf(0) ="
,
math
.
modf
(
0
)
)
(
"math.modf(-8) ="
,
math
.
modf
(
8
)
)
Result:
math.modf(5) = (0.0, 5.0)
math.modf(0) = (0.0, 0.0)
math.modf(-8) = (-0.0, -8.0)
Example 4: practical application - splitting amounts of money
Example
import
math
Split an amount: yuan, jiao, fen
price
=
12.58
fractional
,
integer
=
math
.
modf
(
price
)
yuan
=
int
(
integer
)
jiao
=
int
(
fractional *
10
)
fen
=
int
(
(
fractional *
10
- jiao
)
10
)
(
f
"Price {price} yuan = {yuan} yuan {jiao} jiao {fen} fen"
)
Time conversion: hours to hours:minutes:seconds
hours
=
73.5
fractional_hours
,
whole_hours
=
math
.
modf
(
hours
)
total_minutes
=
fractional_hours *
60
fractional_minutes
,
whole_minutes
=
math
.
modf
(
total_minutes
)
seconds
=
fractional_minutes *
60
(
f
"{hours} hours = {int(whole_hours)} hours {int(whole_minutes)} minutes {int(seconds)} seconds"
)
Result:
价格 12.58 元 = 12 元 5 角 7 分
73.5 小时 = 73 时 30 分 0 秒
Notes
- The returned integer part is a floating-point type, such as 3.0 rather than 3
- The integer part uses "truncation toward zero", unlike floor
- Floating-point numbers have precision errors, so results may have small deviations
Python math Module