Create an array of repeating elements that increase by 0.1 intervals

Kim*_*Lee 0 python arrays numpy scipy python-2.7

What I want my code to do is to create an array of elements: [13.8, 13.9, 14.,...] That increase by 0.1, but each of the elements should repeat 17 times before going on to the next number. Below is my code.

from numpy import*
from pylab import*
def f(elem):
return repeat((elem + 0.1),17)
print f(13.8)

def lst(init):
   yield init
   while True:
       next = f(init)
       yield next
       init = next

for i in lst(13.8):
    print i
    if i > 20:
        break
Run Code Online (Sandbox Code Playgroud)

The output of code only shows an array 13.9 repeating 17 times, but then it shows error:

Traceback (most recent call last):
  File "repeatelementsarray.py", line 19
    if i > 20:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
Run Code Online (Sandbox Code Playgroud)

It seems the program is trying to create more than one array of numbers, I just want one array. Also since lst is a generator it shouldn't give an array, so using fromiter?

ali*_*i_m 5

You can use a combination of np.arange to get the linearly increasing sequence, and np.repeat to repeat each element:

import numpy as np

elems = np.arange(0, 1, 0.1)
reps = np.repeat(elems, 3)

print(reps)
# [ 0.   0.   0.   0.1  0.1  0.1  0.2  0.2  0.2  0.3  0.3  0.3  0.4  0.4  0.4
#   0.5  0.5  0.5  0.6  0.6  0.6  0.7  0.7  0.7  0.8  0.8  0.8  0.9  0.9  0.9]
Run Code Online (Sandbox Code Playgroud)

  • 我同意!但是给 `arange` 一个浮点增量很容易出现一对一的问题。例如,我对 `arange(13.5, 13.9, 0.1)` 和 `arange(13.5, 14.0, 0.1)` 得到相同的答案。 (3认同)
  • 我建议使用 `np.linspace` 而不是 `np.arange`。由于浮点不精确,`np.arange` 给出意外数量的元素并不罕见。 (2认同)