Why when I perform
g = np.float16([4.4,4.6])
I get something different
g = [4.3984..., 4.6015...].
Will it somehow affect calculations with the matrix? Can I change this behavior without changing dtype? Thanks!
Why when I perform
g = np.float16([4.4,4.6])
I get something different
g = [4.3984..., 4.6015...].
Will it somehow affect calculations with the matrix? Can I change this behavior without changing dtype? Thanks!
First of all, you have to cast float16
back to a float
to get that result. You aren't getting a different result though, that's the actual value.
You can't represent 4.4
or 0.3
and many other rational numbers with a floating point number, no matter the precision. Python itself doesn't store 4.4
:
>>> f"{4.4}"
'4.4'
>>> f"{4.4:.15f}"
'4.400000000000000'
>>> f"{4.4:.20f}"
'4.40000000000000035527'
The reason that 4.4
prints as 4.4
is that 15 is the default print precision according to the IEEE 754 floating point number standard.
Using a smaller type increases the error :
>>> f"{np.float64(4.4):.20f}"
'4.40000000000000035527'
>>> f"{np.float32(4.4):.20f}"
'4.40000009536743164062'
>>> f"{np.float16(4.4):.20f}"
'4.39843750000000000000'
NumPy