When I write this code in python:

‘’’

larger_grid_size=0.001

div=larger_grid_size/2

print(div)

print(41.571-div)

‘’’

Why it is printed: 41.570499999999996 instead of 41.5705

Or if I simply do this operation: a=41.571-0.0005, happens the same

When I write this code in python:

‘’’

larger_grid_size=0.001

div=larger_grid_size/2

print(div)

print(41.571-div)

‘’’

Why it is printed: 41.570499999999996 instead of 41.5705

Or if I simply do this operation: a=41.571-0.0005, happens the same

Remember that those `float`

are finite precision floating point and in base 2.

Those `0.001`

, `0.0005`

, and `41.570499999999996`

are decimal representations (think of them as rational numbers in decimal representation that are close to the binary according to the rounding and other features that Python does, like having as few digits as possible).

You can see the binary with

```
import struct
def binary(num):
return ''.join('{:0>8b}'.format(c) for c in struct.pack('!f', num))
```

```
>>> binary(0.1)
'00111101110011001100110011001101'
>>> binary(div)
'00111010000000110001001001101111'
>>> binary(41.571)
'01000010001001100100100010110100'
```

Check in the Wikipedia link the bits that are the sign, the exponent, and the mantissa.

As already pointed out, python’s floats are *binary* floating point numbers. The `repr()`

prints not exact value, rather a decimal approximation to it.

You can see exact value as a hexadecimal floating point number, using float.hex() method:

```
>>> (3.14).hex()
'0x1.91eb851eb851fp+1'
```

It’s a bit weird, but in most cases (excluding decimal numbers, that can be represented exactly as binary, e.g. `0.25`

) - you can create float number from exact known value only with float.fromhex() class method:

```
>>> float.fromhex('0x1.91eb851eb851fp+1')
3.14
```

See also Floating Point Arithmetic: Issues and Limitations in the CPython Tutorial.