[PYTHON] [Sad news] The `np.arange ()` trap that everyone falls into

The trap of np.arange ()

There was an article "Turn a for statement every 0.1 using Python – Kaggle Note".

There are times when you want to repeat the decimal point using a for statement. This time I will write how to achieve it. It is assumed that 0 to 1 are repeated in 0.1 increments.

As it is.

The article mentions "how to use range" and "how to use numpy".

The "method of using range" is as follows.

def myrange():
    gen = range(0, 10, 1)
    return [i/10 for i in gen]


myrange()
# [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]

This is fine code.

Next, the following code is listed as "How to use numpy".

import numpy as np


def myrange2():
    data = np.arange(0.0, 1.0, 0.1)
    data_round = np.round(data, 1)
    return [i for i in data_round]


myrange2()
# [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]

that's no good.

In the case of "0 to 1 in 0.1 increments" this time, there is no problem by chance, but if the value changes, the story changes.

Try "0 to 2.1 in 0.3 increments".

First of all, "How to use range".

def myrange():
    gen = range(0, 21, 3)
    return [i/10 for i in gen]


myrange()
# [0.0, 0.3, 0.6, 0.9, 1.2, 1.5, 1.8]

This is the model answer.

"How to use numpy" is as follows.

import numpy as np


def myrange2():
    data = np.arange(0.0, 2.1, 0.3)
    data_round = np.round(data, 1)
    return [i for i in data_round]


myrange2()
# [0.0, 0.3, 0.6, 0.9, 1.2, 1.5, 1.8, 2.1]

Did you understand? The end is wrong.

** The number of steps in np.arange () should not be given a decimal. **: hugging:

Recommended Posts

[Sad news] The `np.arange ()` trap that everyone falls into