0

I have a list :

a = [1,2,3,4,5,6,7,8,9,10]

I want to add a different random number to each element in the list using np.random.randn() I start by creating another list containing the rando values by using:

noise = []
for i in range(len(a)):
    b = (random_noise * np.random.randn())
    noise.append(b)

And the add the two lists

a + b 

My question is, is there a simplified method in which i can add the noise directly to a elements without the need to creating the loop, in seek of saving time in the large problems.

2
  • 1
    If you want to switch to numpy, which you probably want to do, then you can generate an array of randoms and add that to the original data. In straight Python, it requires a loop. Commented Sep 13, 2022 at 18:16
  • It is syntactic sugar, but you could use a list comprehension. Commented Sep 13, 2022 at 18:19

3 Answers 3

2

If you turn a into a numpy array, you can do

>>> a = np.array(a)
>>> a2 = a + np.random.randn(a.size)
>>> a2
array([-0.1199694 ,  1.64558727,  3.10977101,  5.66627737,  4.95481395,
        7.63834891,  7.48148948,  8.55867759,  8.02858298,  9.77297563])
Sign up to request clarification or add additional context in comments.

Comments

1

Create the noise as np array and add it to a

import numpy as np
a = [1,2,3,4,5,6,7,8,9,10]
noise = np.random.randn(len(a))
print(a+noise)    

Comments

0

You can do something like this:

a = [x + np.random.randn() for x in range(1, 10)]
print(a)

output:

[0.31328085156307206, 0.8473128208005949, 4.574220370196114, 3.7338991251803195, 4.9131070198281686, 5.4760389038550565, 7.328982658187497, 6.716468468134682, 9.491303138695487]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.