Floats in Python
Now, let’s see the float methods:
>>> dir(float)
[‘__abs__’, ‘__add__’, ‘__bool__’, ‘__class__’, ‘__delattr__’, ‘__dir__’, ‘__div
mod__’, ‘__doc__’, ‘__eq__’, ‘__float__’, ‘__floordiv__’, ‘__format__’, ‘__ge__’
, ‘__getattribute__’, ‘__getformat__’, ‘__getnewargs__’, ‘__gt__’, ‘__hash__’, ‘
__init__’, ‘__int__’, ‘__le__’, ‘__lt__’, ‘__mod__’, ‘__mul__’, ‘__ne__’, ‘__neg
__’, ‘__new__’, ‘__pos__’, ‘__pow__’, ‘__radd__’, ‘__rdivmod__’, ‘__reduce__’, ‘
__reduce_ex__’, ‘__repr__’, ‘__rfloordiv__’, ‘__rmod__’, ‘__rmul__’, ‘__round__’
, ‘__rpow__’, ‘__rsub__’, ‘__rtruediv__’, ‘__setattr__’, ‘__setformat__’, ‘__siz
eof__’, ‘__str__’, ‘__sub__’, ‘__subclasshook__’, ‘__truediv__’, ‘__trunc__’, ‘a
s_integer_ratio’, ‘conjugate’, ‘fromhex’, ‘hex’, ‘imag’, ‘is_integer’, ‘real’]
>>>
They are similar to the integer methods.
float.as_integer_ration
>>> h = 2.5
>>> h
2.5
>>> h.as_integer_ratio()
(5, 2)
>>>
>>> g.as_integer_ratio()
(5998794703657501, 18014398509481984)
>>>
We can know the exact value of a float. This method expresses the value of a float as a fraction. We can recreate the original value:
>>> 5/2
2.5
>>>
>>> 5998794703657501/18014398509481984
0.333
>>>
float.hex()
>>> h.hex()
‘0x1.4000000000000p+1’
>>> g.hex()
‘0x1.54fdf3b645a1dp-2’
>>>
We can express a float in hexadecimal (base 16).
float.fromhex()
>>> h.fromhex(‘0x1.4000000000000p+1’)
2.5
>>> g.fromhex(‘0x1.54fdf3b645a1dp-2’)
0.333
We can restore them.
float.conjugate() -> int
>>> w.conjugate()
4
>>> v.conjugate()
2345
>>>
We can identity on real numbers in the complex numbers.
float.imag
>>> w.imag
0
>>>
>>> v.imag
0
>>>
We can know if our float has an imaginary unit. If not, we’ll get 0.
float.real
>>> w.real
4
>>> v.real
234
>>>
We can know if our float is a real number.
float.is_integer()
>>> h.is_integer()
False
>>> g.is_integer()
False
>>>
>>> f = 10.0
>>> f.is_integer()
True
We can know if our float is integer or not.