Annoying loss of precision when transforming numpy array to list

Dear Python experts,

I am seeing this:

In [15]: numpy.linspace(-1, +1, 10 + 1,).tolist()
Out[15]:
[-1.0,
 -0.8,
 -0.6,
 -0.3999999999999999,
 -0.19999999999999996,
 0.0,
 0.20000000000000018,
 0.40000000000000013,
 0.6000000000000001,
 0.8,
 1.0]

In [16]:

i.e. there is a loss of precision when going to a list. I will later convert the floats into strings like 0p4 and this will mess up things. Do you know how to prevent this?

Cheers.

There is no loss of precision, floating point numbers just aren’t precises: https://0.30000000000000004.com/

numpy might be default cut the numbers of earlier, but you can do the same with options for your string conversion.

If it is a choice that you can make, use 1, 2 and 2^n+1 as the number of elements: 1,2,3,5,9,17,33,65, 129, ....

See also 15. Floating Point Arithmetic: Issues and Limitations — Python 3.12.4 documentation

Not all numbers are representable as a (finite) binary (floating point) number. For example 1/5=0.2 is not, similar to how 1/3=0.3333… is not representable as a (finite) decimal number.

The values you get are probably the (exact) floating point values that are closest to the real numbers you want.