Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python math.modf() Function

Python math.modf() Function

Python math Module Python math Module


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

Return Value


Example

Example 1: basic usage

Example

import

math

result

=

math

.

modf

(

3.14159

)

print

(

"math.modf(3.14159) ="

,

result

)

fractional

,

integer

=

math

.

modf

(

3.14159

)

print

(

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

print

(

"math.modf(-3.14) ="

,

math

.

modf

(

3.14

)

)

print

(

"math.modf(-0.5) ="

,

math

.

modf

(

0.5

)

)

fractional

,

integer

=

math

.

modf

(

3.14

)

print

(

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

print

(

"math.modf(5) ="

,

math

.

modf

(

5

)

)

print

(

"math.modf(0) ="

,

math

.

modf

(

0

)

)

print

(

"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

)

10

)

print

(

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

print

(

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


Python math Module Python math Module