TThe
TThe

Reputation: 69

Why do the values in the for loop not correspond to those in Numpys arange and linspace?

I simply try to iterate through a sequence, but the values always change slightly, it is only noticeable when you try to save files with the appropriate name. I started with Numpys arange, but since the documentation says that the values can differ if the steps are not integer, I switched to linspace as recommended.

import numpy as np
seq = np.linspace(0.01, 0.09,9)
seq2 = ([])
for i in seq:
    seq2.append(i)

Seq is: array([0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, 0.09])
Seq2 is: [0.01, 0.02, 0.03, 0.04, 0.05, 0.060000000000000005, 0.06999999999999999, 0.08, 0.09]
Could someone explain to me what this issue is about?
Thanks in advance
Im working on Python 3.6.7 and Numpy 1.14

Upvotes: 0

Views: 90

Answers (1)

Patrick Artner
Patrick Artner

Reputation: 51643

TL/DR: Its a display issue with numpy.ndarray displaying things differently - you can customize the printing:

import numpy as np
import sys
np.set_printoptions(precision=20)
seq = np.linspace(0.01, 0.09,9)
print(seq)

[0.01                 0.02                 0.03
 0.04                 0.05                 0.060000000000000005
 0.06999999999999999  0.08                 0.09                ]

See How to pretty-print a numpy.array without scientific notation and with given precision?

You still got floats inside and "Is floating point math broken?" applies:

import numpy as np
seq = np.linspace(0.01, 0.09,9)
seq2 = ([])
for i in seq:
    seq2.append(i)

print(*seq)
print(*seq2)

Output:

0.01 0.02 0.03 0.04 0.05 0.060000000000000005 0.06999999999999999 0.08 0.09
0.01 0.02 0.03 0.04 0.05 0.060000000000000005 0.06999999999999999 0.08 0.09

Upvotes: 1

Related Questions