0

I'm trying to make a line with scattered points around the function y = 2x. The points should have a random deviation between -0.5 and 0.5 compared to the normal function (which is f(x)):

def f(x):
    return 2 * x

def g(x):
    return f(x) - np.random.uniform(-0.5, 0.5)

x = np.linspace(0, 5, 51)
y = f(x)
y2 = g(x)

# plot
plt.plot(t, y, 'b-')
plt.plot(t, y, 'ro')
plt.show()

And ofcourse, y2 will now be a scattered line where all the points have the same deviation because the random number is the same for all the points. Now I wonder how I could make it so each point will have a random deviation (so how can I perform an action on each point individualy). Thanks in advance!

1 Answer 1

1

Yes: pass size=(51,) (or better, use the shape of the x array) to np.random.uniform() to draw that many samples from the uniform distribution:

import numpy as np
import matplotlib.pyplot as plt
def f(x):
    return 2 * x

def g(x):
    return f(x) - np.random.uniform(-0.5, 0.5, size=x.shape)

x = np.linspace(0, 5, 51)
y = f(x)
y2 = g(x)

# plot
plt.plot(x, y, 'b-')
plt.plot(x, y2, 'ro')
plt.show()

enter image description here

Sign up to request clarification or add additional context in comments.

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.