World Languages, asked by muhsin02062003, 2 months ago

Given a positive real number, print its fractional part.





\

Answers

Answered by shijojoy1234
0

Answer:

math.modf() can be used to get the fractional and integer parts of a number simultaneously.

math.modf() — Mathematical functions — Python 3.7.4 documentation

See the following article for divmod() which return the quotient and remainder.

Get quotient and remainder with divmod() in Python

Explanation:

Applying int() to the floating-point number float, you can get the integer part.

Using this, the fractional and integer parts can be obtained.

a = 1.5

i = int(a)

f = a - int(a)

print(i)

print(f)

# 1

# 0.5

print(type(i))

print(type(f))

# <class 'int'>

# <class 'float'>

Get the fractional and integer parts with math.modf()

modf() in the math module can be used to get the fractional and the integer parts of a number at the same time.

math.modf() returns a tuple (fractional part, integer part).

import math

print(math.modf(1.5))

print(type(math.modf(1.5)))

# (0.5, 1.0)

# <class 'tuple'>

Each can be assigned to a variable using unpacking. Both the fractional and the integer parts are float.

Unpack a tuple / list in Python

f, i = math.modf(1.5)

print(i)

print(f)

# 1.0

# 0.5

print(type(i))

print(type(f))

# <class 'float'>

# <class 'float'>

source: math_modf.py

The sign is the same as the original value.

f, i = math.modf(-1.5)

print(i)

print(f)

# -1.0

# -0.5

source: math_modf.py

math.modf() can also be applied to the int. Again, both the fractional and integer parts are float.

f, i = math.modf(100)

print(i)

print(f)

# 100.0

# 0.0

source: math_modf.py

Whether float is an integer (the fractional part is 0) can be checked with float method is_integer() without obtaining the fractional part. See the following article.

Check if a number is integer or decimal in Python.

Similar questions