The float
type in Python represents the floating point number. Float is used to represent real numbers and is written with a decimal point dividing the integer and fractional parts. For example, 97.98, 32.3+e18, -32.54e100 all are floating point numbers.
Python float values are represented as 64-bit double-precision values. The maximum value any floating-point number can be is approx 1.8 x 10308. Any number greater than this will be indicated by the string inf
in Python.
print ( 1.7e308 )
print ( 1.82e308 )
|
Output:
1.7e+308
inf
Floating-point numbers are represented in computer hardware as base 2 (binary) fractions. For example, the decimal fraction 0.125 has value 1/10 + 2/100 + 5/1000, and in the same way the binary fraction 0.001 has value 0/2 + 0/4 + 1/8. These two fractions have identical values, the only real difference being that the first is written in base 10 fractional notation, and the second in base 2.
Unfortunately, most decimal fractions cannot be represented exactly as binary fractions. A consequence is that, in general, the decimal floating-point numbers you enter are only approximated by the binary floating-point numbers actually stored in the machine.
The float
type implements the numbers.Real
abstract base class. Returns an expression which is converted into floating point number. float
also has the following additional methods:
float.as_integer_ratio() : Returns a pair of integers whose ratio is exactly equal to the actual float having a positive denominator.In case of infinites, it raises overflow error and value errors on Not a number (NaNs).
def frac(d):
b = d.as_integer_ratio()
return b
if __name__ = = '__main__' :
b = frac( 3.5 )
print (b[ 0 ], "/" , b[ 1 ])
|
Output:
7 / 2
float.is_integer() : Returns True in case the float instance is finite with integral value, else, False.
def booln():
print (( - 5.0 ).is_integer())
print (( 4.8 ).is_integer())
print ( float .is_integer( 275.0 ))
if __name__ = = '__main__' :
booln()
|
Output:
True
False
True
float.hex() : Returns a representation of a floating-point number as a hexadecimal string.
def frac(a):
a = float . hex ( 35.0 )
return a
if __name__ = = '__main__' :
b = frac( 35.0 )
print (b)
|
Output:
'0x1.1800000000000p+5'
float.fromhex(s) : Returns the float represented by a hexadecimal string s. String s may have leading and trailing whitespaces.
def frac(a):
a = float .fromhex( '0x1.1800000000000p+5' )
return a
if __name__ = = '__main__' :
b = frac( '0x1.1800000000000p+5' )
print (b)
|
Output:
35.0
Note : float.hex() is an instance method, but float.fromhex() is a class method.
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!